Dup Ver Goto 📝

basics

PT2/lang/php/arrays does not exist
To
70 lines, 180 words, 1148 chars Page 'basics' does not exist.

merge (concat or update)

  <?php
$a = [ "a", "b", "c" ];
$b = [ "d", "e" ];
$c = array_merge($a,$b); # concatenates
var_dump($c);

$a = [ "a" => "mr", "b" => "flibble", "tony" => "tiger" ];
$b = [ "a" => "hex", "b" => "vision", "percy" => "penguin" ];
$c = array_merge($a,$b); # overwrites
var_dump($c);

prints out

array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}
array(4) {
  ["a"]=>
  string(3) "hex"
  ["b"]=>
  string(6) "vision"
  ["tony"]=>
  string(5) "tiger"
  ["percy"]=>
  string(7) "penguin"
}

Filter and map — arg order

I keep forgetting the order of these.

array_filter($array,$f);
array_map($f,$array);

example

<?php
$a = ["a","b","c"];
$b = array_filter($a,function($x) { return $x !== "c"; });
echo implode(", ",$b)."\n";

$a = ["a","b","c"];
$b = ["d","e"];
$c = array_map(function($x) { return "hello $x\n"; },$a,$b);
echo implode("",$c); 

prints

a, b
hello a
hello b
hello c

Not copying

When we assign an array, it copies by default.

$a = &$array;
$a = &$object->member_array;