A few rules about how PHP arrays behave catch many beginners. Learn them once.
Arrays are copied on assignment
Unlike objects, arrays are values. Assigning an array to another variable gives you an independent copy.
<?php
$a = [1, 2, 3];
$b = $a;
$b[] = 4;
echo count($a) . " vs " . count($b);
3 vs 4
The same is true when you pass an array to a function. The function changes its own copy (unless you use &).
Keys are converted
PHP changes some keys to integers.
<?php
$data = [];
$data["5"] = "text five"; // becomes the integer 5
$data[true] = "true"; // becomes 1
$data[null] = "null"; // becomes ""
var_dump(array_keys($data));
array(3) {
[0]=>
int(5)
[1]=>
int(1)
[2]=>
string(0) ""
}
A key like "05" stays a string, because it is not a plain integer.
Duplicate keys overwrite
<?php
$a = ["x" => 1, "x" => 2];
echo $a["x"];
2
The next free index
When you add with [], PHP uses the highest integer key plus one.
<?php
$list = [5 => "a"];
$list[] = "b";
print_r($list);
Array
(
[5] => a
[6] => b
)
Order is kept
PHP arrays remember the order you added items in. That is why foreach gives items back in that order. Sorting functions change it.
Nested arrays are copied too
<?php
$config = ["db" => ["host" => "localhost"]];
$copy = $config;
$copy["db"]["host"] = "remote";
echo $config["db"]["host"];
localhost
Objects inside arrays are shared
Arrays of objects copy the array, but each object is still the same one.
<?php
$user = new stdClass();
$user->name = "Ana";
$list = [$user];
$copy = $list;
$copy[0]->name = "Changed";
echo $list[0]->name;
Changed
Reading a missing key
<?php
$a = ["x" => 1];
echo $a["y"] ?? "missing";
missing
Without ??, PHP 8 raises a warning: Undefined array key "y". Do not hide such warnings. They point to real bugs.
Arrays can be compared and counted
You saw == and === in Array Operators.
Use arrays for lists and records
[]. For a record, use string keys. If you find yourself writing $data["items"][0]["tags"][2] often, an object or a small class may be clearer.