MENU
Arrays
In PHP, an array is an ordered map that associates keys to values. A key can be an integer or a string. These two statements do the same assignment:$arr = array(“a”=>”Hello”, 5 => “World”);
$arr = [“a”=>”Hello”, 5 => “World”]; // PHP 5.4+
If a key is a float, a string containing an integer or a boolean, it will be cast to an integer. If the key is not specified, it will be regarded as the largest integer index plus 1. Eg.:
$arr = [“orange”, // key 0
”apple”, // key 1
5.7=> “pineapple”, // key 5
“special” => “cucumber”, // key “special”
“watermelon”]; // key 6
$arr[]=”pear”; // key 7
To access $arr, use the square brackets [], eg.: $arr[1], $arr[“special”].
Assign an array to a key in an array to create a multidimensional array.
$arr = [“ma”=>[“foo”=>”bar”]];
$arr[1][2] = “live”;
To access the value “foo”, use $arr[“ma”][“foo”].
Applying the + operator to two arrays returns an array which is a union of the two arrays. If the arrays contain the same keys, the key-value pairs of the left operand will be preserved.
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$a=[4,5,6];
$b=[1,2,3,7,8];
var_dump ($a + $b);
?></body>
</html>array(5) { [0]=> int(4) [1]=> int(5) [2]=> int(6) [3]=> int(7) [4]=> int(8) }
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$a=["hello","hi"];
$b=[1=>"hi",0=>"hello"];
var_dump ($a==$b); // true; same key-value pairs
var_dump ($a===$b); // false; different order
var_dump ($a!==$b); // true; different order
var_dump ($a<>$b); // false; same key-value pairs
var_dump ($a!=$b); // false; same key-value pairs
?></body>
</html>bool(true) bool(false) bool(true) bool(false) bool(false)
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$arr = ['apple',2=>'orange','mango'];
list($a0,,,$a3)=$arr; // index 1 and index 2 skipped
echo ($a0." ".$a3."<br />");
list($a,list($b,$c)) = ['fruits',['vege','meat']]; // nested
echo ($a." ".$b." ".$c);
?></body>
</html>apple mango
fruits vege meat
Spreading numerically-keyed arrays re-indexes them from 0:
<?php
$a = [1, 2, 3];
$b = [0, ...$a, 4, 5];
print_r($b);
?>Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
Spreading string-keyed arrays (PHP 8.1+): the later "b" overwrites the earlier one:
Since PHP 7.1, list() (and its short [] syntax) can destructure an associative array by naming which key goes into which variable, using the same key => $variable syntax as an array literal. This also means the target variables no longer need to follow the original array's order:
<?php
$assoc1 = ["a" => 1, "b" => 2];
$assoc2 = ["b" => 3, "c" => 4];
$merged = [...$assoc1, ...$assoc2];
print_r($merged);
?>Array
(
[a] => 1
[b] => 3
[c] => 4
)
<?php
$data = ['id' => 42, 'name' => 'Alice', 'role' => 'admin'];
['id' => $id, 'name' => $name] = $data;
echo "$id - $name\n";
list('name' => $n, 'role' => $r) = $data;
echo "$n - $r\n";
?>42 - Alice
Alice - admin
<?php
$arr = [1, 2, 3];
[&$a, &$b, $c] = $arr;
$a = 10;
$b = 20;
print_r($arr);
?>Array
(
[0] => 10
[1] => 20
[2] => 3
)