Creating Arrays
<?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
$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
$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
$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
$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
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
$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
$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
$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
| Function | What it does | Preserves keys? |
|---|---|---|
sort() | Ascending by value | No (re-indexes) |
rsort() | Descending by value | No |
asort() | Ascending by value | Yes |
arsort() | Descending by value | Yes |
ksort() | Ascending by key | Yes |
krsort() | Descending by key | Yes |
usort() | Custom comparator | No |
uasort() | Custom comparator | Yes |
<?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
$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
// 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