Skip to content

PHP Tutorial Arrays

Array Behaviour You Should Know

Lesson 132 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.

index.php
PHP
<?php
$a = [1, 2, 3];
$b = $a;

$b[] = 4;

echo count($a) . " vs " . count($b);
Output
OUTPUT
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.

index.php
PHP
<?php
$data = [];
$data["5"] = "text five";   // becomes the integer 5
$data[true] = "true";       // becomes 1
$data[null] = "null";       // becomes ""

var_dump(array_keys($data));
Output
OUTPUT
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

index.php
PHP
<?php
$a = ["x" => 1, "x" => 2];

echo $a["x"];
Output
OUTPUT
2

The next free index

When you add with [], PHP uses the highest integer key plus one.

index.php
PHP
<?php
$list = [5 => "a"];
$list[] = "b";

print_r($list);
Output
OUTPUT
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

index.php
PHP
<?php
$config = ["db" => ["host" => "localhost"]];
$copy = $config;

$copy["db"]["host"] = "remote";

echo $config["db"]["host"];
Output
OUTPUT
localhost

Objects inside arrays are shared

Arrays of objects copy the array, but each object is still the same one.

index.php
PHP
<?php
$user = new stdClass();
$user->name = "Ana";

$list = [$user];
$copy = $list;

$copy[0]->name = "Changed";

echo $list[0]->name;
Output
OUTPUT
Changed

Reading a missing key

index.php
PHP
<?php
$a = ["x" => 1];

echo $a["y"] ?? "missing";
Output
OUTPUT
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.

lightbulb
Use arrays for lists and records
For a list, use integer keys and []. 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.