beginner
Step 5 of 16
Arrays and Array Functions
PHP Programming
Arrays and Array Functions
Arrays are the most important and versatile data structure in PHP. Unlike most other languages, PHP arrays serve as both indexed arrays (lists) and associative arrays (dictionaries/maps). They are ordered, can hold mixed types, and come with over 80 built-in array functions. PHP arrays are used everywhere — for configuration, request data, database results, API responses, and function arguments. Mastering array manipulation is arguably the single most important skill for PHP development.
Creating and Accessing Arrays
<?php
// Indexed arrays
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // "apple"
echo $fruits[-1]; // Error! PHP doesn't support negative indices like Python
// Associative arrays
$person = [
"name" => "Alice",
"age" => 30,
"city" => "New York"
];
echo $person["name"]; // "Alice"
// Multi-dimensional arrays
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // 6
// Adding elements
$fruits[] = "date"; // Append
$fruits[10] = "elderberry"; // Sparse — index 10
$person["email"] = "alice@example.com"; // Add key
// Array unpacking (PHP 7.4+)
$first = [1, 2, 3];
$second = [4, 5, 6];
$combined = [...$first, ...$second]; // [1, 2, 3, 4, 5, 6]
// Named keys unpacking (PHP 8.1+)
$defaults = ['color' => 'blue', 'size' => 'M'];
$custom = ['color' => 'red'];
$merged = [...$defaults, ...$custom]; // color=red, size=M
?>
Essential Array Functions
<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
// Sorting
sort($numbers); // [1, 1, 2, 3, 4, 5, 6, 9] — modifies in place
rsort($numbers); // Reverse sort
$users = [['name' => 'Bob'], ['name' => 'Alice']];
usort($users, fn($a, $b) => $a['name'] <=> $b['name']);
// Searching
$fruits = ["apple", "banana", "cherry", "banana"];
echo in_array("banana", $fruits); // true
echo array_search("cherry", $fruits); // 2 (index)
echo array_key_exists("name", $person); // true
// Slicing and splicing
$slice = array_slice($fruits, 1, 2); // ["banana", "cherry"]
array_splice($fruits, 1, 1); // Remove 1 element at index 1
// Merging
$a = [1, 2, 3];
$b = [4, 5, 6];
$merged = array_merge($a, $b); // [1, 2, 3, 4, 5, 6]
// Unique values
$dupes = [1, 2, 2, 3, 3, 3];
$unique = array_unique($dupes); // [1, 2, 3]
// Flipping keys and values
$colors = ["r" => "red", "g" => "green"];
$flipped = array_flip($colors); // ["red" => "r", "green" => "g"]
// Counting values
$votes = ["yes", "no", "yes", "yes", "no"];
$counts = array_count_values($votes); // ["yes" => 3, "no" => 2]
// Column extraction from 2D array
$users = [
["name" => "Alice", "age" => 30],
["name" => "Bob", "age" => 25],
["name" => "Charlie", "age" => 35],
];
$names = array_column($users, "name"); // ["Alice", "Bob", "Charlie"]
$by_name = array_column($users, null, "name"); // Indexed by name
?>
Functional Array Operations
<?php
$products = [
["name" => "Laptop", "price" => 999, "category" => "electronics"],
["name" => "Book", "price" => 15, "category" => "education"],
["name" => "Phone", "price" => 699, "category" => "electronics"],
["name" => "Pen", "price" => 2, "category" => "office"],
["name" => "Tablet", "price" => 499, "category" => "electronics"],
];
// Filter expensive electronics
$expensive = array_filter($products, fn($p) =>
$p['category'] === 'electronics' && $p['price'] > 500
);
// Extract names
$names = array_map(fn($p) => $p['name'], $expensive);
// ["Laptop", "Phone"]
// Calculate total price
$total = array_reduce($products, fn($sum, $p) => $sum + $p['price'], 0);
echo "Total: $total
"; // 2214
// Group by category
$grouped = [];
foreach ($products as $product) {
$grouped[$product['category']][] = $product;
}
print_r($grouped);
// array_walk — modify each element in place
$prices = [10.0, 20.0, 30.0];
array_walk($prices, function(&$price, $key) {
$price = round($price * 1.1, 2); // Add 10% tax
});
?>
Destructuring Arrays
<?php
// List assignment / array destructuring
[$first, $second, $third] = ["red", "green", "blue"];
echo $first; // "red"
// Skip elements
[, , $third] = [1, 2, 3];
echo $third; // 3
// Named keys
["name" => $name, "age" => $age] = ["name" => "Alice", "age" => 30];
echo "$name is $age"; // "Alice is 30"
// In foreach
$users = [
["name" => "Alice", "age" => 30],
["name" => "Bob", "age" => 25],
];
foreach ($users as ["name" => $name, "age" => $age]) {
echo "$name: $age
";
}
?>
Pro tip: Learnarray_column()— it is one of the most useful but underused array functions. It extracts a single column from a multi-dimensional array, saving you from writing a loop orarray_map()call. Combined with its third parameter for re-indexing, it is incredibly powerful for restructuring database results.
Key Takeaways
- PHP arrays serve as both indexed lists and associative maps — they are the most versatile PHP data structure.
- Use
array_map(),array_filter(), andarray_reduce()for functional-style data processing. array_column()extracts values from multi-dimensional arrays without loops.- Array destructuring with
[$a, $b] = $arrayprovides clean variable extraction. - Most array sort functions modify the array in place; use
usort()with the spaceship operator for custom sorting.