PHP Arrays

Arrays are PHP's universal collection - lists, maps, stacks, queues, and trees, all in one type. Master 25 essential functions and the modern array idioms.

Beginner 12 min read 20 examples

Creating Arrays

PHP
<?php
// Short syntax (PHP 5.4+) - always use this
$fruits = ["apple", "banana"];

// Long syntax - legacy code only
$fruits = array("apple", "banana");

// Empty array
$empty = [];

// From a range
$nums = range(1, 5);     // [1,2,3,4,5]
$abc  = range("a", "e"); // ["a","b","c","d","e"]

// Fill with a single value
$zeros = array_fill(0, 5, 0); // [0,0,0,0,0]

Indexed Arrays

Numeric keys, starting at 0:

PHP
<?php
$fruits = ["apple", "banana", "cherry"];

echo $fruits[0];        // apple
echo $fruits[2];        // cherry
echo count($fruits);    // 3

// Modify
$fruits[1] = "blueberry";

// Append
$fruits[] = "date";     // adds at end

// Reverse
$rev = array_reverse($fruits);

Associative Arrays

String keys mapped to values - PHP's equivalent of a dictionary or hash map:

PHP
<?php
$user = [
    "name"  => "Ruban",
    "email" => "ruban@example.com",
    "age"   => 30,
    "admin" => true,
];

echo $user["name"];

// Safer access (PHP 7+) - returns null instead of warning
$role = $user["role"] ?? "guest";

// Get all keys / values
$keys   = array_keys($user);     // ["name","email","age","admin"]
$values = array_values($user);   // ["Ruban","ruban@example.com",30,true]

Multi-dimensional Arrays

PHP
<?php
$users = [
    ["name" => "Alice", "age" => 30],
    ["name" => "Bob",   "age" => 25],
    ["name" => "Cara",  "age" => 35],
];

echo $users[1]["name"];   // Bob

// 2D matrix
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
echo $matrix[2][1];       // 8

// Add a new row
$users[] = ["name" => "Dan", "age" => 40];

Looping with foreach

PHP
<?php
$fruits = ["apple", "banana", "cherry"];

// Just values
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

// With index
foreach ($fruits as $i => $fruit) {
    echo "$i: $fruit\n";
}

// Associative
$user = ["name" => "Ruban", "age" => 30];
foreach ($user as $key => $value) {
    echo "$key: $value\n";
}

// By reference - modify in place
foreach ($fruits as &$f) {
    $f = strtoupper($f);
}
unset($f);   // CRITICAL - break the reference
Always unset after by-reference foreach

If you use foreach ($arr as &$item), you must unset($item); after the loop. The reference lingers and the next assignment to $item will silently overwrite the last array element - a classic PHP bug.

Adding & Removing Items

PHP
<?php
$arr = [1, 2, 3];

// Append (end)
$arr[]        = 4;
array_push($arr, 5, 6);   // can push multiple

// Prepend (start)
array_unshift($arr, 0);

// Pop (remove last)
$last = array_pop($arr);

// Shift (remove first)
$first = array_shift($arr);

// Remove specific key
unset($arr[1]);
// Re-index after unset:
$arr = array_values($arr);

// Slice and splice
$slice  = array_slice($arr, 1, 2);
array_splice($arr, 1, 2, ["x", "y"]);   // remove and insert

Checking Keys & Values

PHP
<?php
$arr = ["name" => "Ruban", "email" => "x@y.com", "phone" => null];

// Key checks
var_dump(isset($arr["name"]));                // true
var_dump(isset($arr["phone"]));               // false (null counts as missing)
var_dump(array_key_exists("phone", $arr));    // true (null is set)

// Value checks
var_dump(in_array("Ruban", $arr));             // true
var_dump(in_array("ruban", $arr, true));       // false (strict)

// Find key by value
$key = array_search("Ruban", $arr);            // "name"

// Count
echo count($arr);
echo count($matrix, COUNT_RECURSIVE);   // count nested too

Transforming (map / filter / reduce)

PHP
<?php
$nums = [1, 2, 3, 4, 5];

// map - transform each
$squares = array_map(fn($n) => $n * $n, $nums);
// [1, 4, 9, 16, 25]

// filter - keep matching
$even = array_filter($nums, fn($n) => $n % 2 === 0);
// [1 => 2, 3 => 4]   <- keys preserved!
$even = array_values($even);  // re-index

// reduce - collapse to single value
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
// 15

// Combine: sum of squares of evens
$result = array_sum(
    array_map(fn($n) => $n * $n,
        array_filter($nums, fn($n) => $n % 2 === 0)
    )
);  // 20

Sorting

FunctionWhat it doesPreserves keys?
sort()Ascending by valueNo (re-indexes)
rsort()Descending by valueNo
asort()Ascending by valueYes
arsort()Descending by valueYes
ksort()Ascending by keyYes
krsort()Descending by keyYes
usort()Custom comparatorNo
uasort()Custom comparatorYes
PHP
<?php
$users = [
    ["name" => "Alice", "age" => 30],
    ["name" => "Bob",   "age" => 25],
    ["name" => "Cara",  "age" => 35],
];

// Sort by age ascending
usort($users, fn($a, $b) => $a["age"] <=> $b["age"]);

// Sort by name
usort($users, fn($a, $b) => strcmp($a["name"], $b["name"]));

Merging & Combining

PHP
<?php
$defaults = ["theme" => "light", "lang" => "en", "size" => 12];
$user     = ["theme" => "dark"];

// array_merge - user overrides defaults
$config = array_merge($defaults, $user);
// ["theme" => "dark", "lang" => "en", "size" => 12]

// + operator (union) - keeps left value on collision
$config = $user + $defaults;
// same result here

// Combine separate keys + values arrays
$keys   = ["a", "b", "c"];
$values = [1, 2, 3];
$assoc  = array_combine($keys, $values); // ["a"=>1, "b"=>2, "c"=>3]

// Flatten nested array
$flat   = array_merge(...$matrix);   // requires PHP 7.4+

// Extract one column from rows
$names  = array_column($users, "name");
$byId   = array_column($users, null, "id"); // key by id

Destructuring & Spread

PHP
<?php
// Numeric destructuring
[$a, $b, $c] = [1, 2, 3];

// Associative destructuring (PHP 7.1+)
["name" => $name, "age" => $age] = $user;

// Skip with empty slot
[, $second, , $fourth] = [1, 2, 3, 4];

// Spread in arrays (PHP 7.4+)
$head = [1, 2];
$tail = [3, 4];
$all  = [...$head, ...$tail];        // [1,2,3,4]

// Spread with string keys (PHP 8.1+)
$a = ["x" => 1];
$b = ["y" => 2];
$c = [...$a, ...$b];                 // ["x"=>1,"y"=>2]

// Spread into function args
function add($a, $b) { return $a + $b; }
echo add(...[3, 4]);                 // 7

Next Steps

Frequently Asked Questions

array_merge() renumbers integer keys and overwrites string keys with later values. The + operator (union) keeps the first array's values when keys collide. For string keys you usually want array_merge(); for numeric union behavior use +.

array_map is great when transforming each element to a new one. foreach wins when you need the index, multiple results, conditional logic, or side effects. Don't force array_map if foreach reads more naturally.

Because PHP arrays are ordered maps, keys are first-class. To re-index after filtering, wrap it: array_values(array_filter($arr)).

isset($arr[$key]) is the fastest but treats null values as "missing". array_key_exists($key, $arr) returns true for null values too. Use isset when you want "has a real value", array_key_exists when null counts as present.

Yes. $mix = [1, "two", 3.0, true, null, [4, 5]]; is perfectly valid. PHP arrays are heterogeneous - which is convenient but lose the safety of typed collections found in other languages.