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