Master PHP arrays - from basic indexed arrays to advanced multi-dimensional structures and powerful array functions
Arrays are one of PHP's most powerful and versatile data structures. They can store multiple values under a single variable name, making them essential for managing collections of data. Whether you're working with user lists, product catalogs, or configuration settings, arrays are fundamental to PHP development.
PHP arrays are extremely flexible - a single array can contain different data types, act as both a list and a map, and even hold other arrays to create complex nested structures. This flexibility, combined with PHP's extensive library of array functions, makes arrays the go-to solution for data manipulation tasks.
In this lesson, you'll master array creation, manipulation, and transformation. You'll learn powerful array functions that can filter data, transform values, sort collections, and reduce arrays to single values. By the end, you'll be able to handle complex data processing tasks with confidence.
PHP supports several array types, each suited for different use cases. Understanding when to use each type is key to writing clean, efficient code.
Indexed Arrays:
Arrays with numeric keys starting from 0:
1// Short array syntax (modern, preferred)
2$colors = ['red', 'green', 'blue'];
3
4// Traditional syntax
5$fruits = array('apple', 'banana', 'cherry');
6
7// Accessing elements
8echo $colors[0]; // "red"
9echo $colors[1]; // "green"
10
11// Adding elements
12$colors[] = 'yellow'; // Appends to end
13$colors[10] = 'purple'; // Specific indexAssociative Arrays:
Arrays with string keys (like maps or dictionaries):
1$user = [
2 'name' => 'John Doe',
3 'email' => '[email protected]',
4 'age' => 30,
5 'role' => 'admin'
6];
7
8echo $user['name']; // "John Doe"
9echo $user['email']; // "[email protected]"
10
11// Adding/updating
12$user['phone'] = '+1-555-0123';
13$user['age'] = 31; // Update existingMulti-Dimensional Arrays:
Arrays containing other arrays:
1$users = [
2 ['name' => 'John', 'age' => 30, 'city' => 'New York'],
3 ['name' => 'Jane', 'age' => 25, 'city' => 'Los Angeles'],
4 ['name' => 'Bob', 'age' => 35, 'city' => 'Chicago']
5];
6
7echo $users[0]['name']; // "John"
8echo $users[1]['city']; // "Los Angeles"
9
10// Nested associative arrays
11$config = [
12 'database' => [
13 'host' => 'localhost',
14 'port' => 3306,
15 'credentials' => [
16 'username' => 'root',
17 'password' => 'secret'
18 ]
19 ],
20 'cache' => [
21 'driver' => 'redis',
22 'ttl' => 3600
23 ]
24];
25
26echo $config['database']['credentials']['username']; // "root"Array Initialization:
1// Empty array
2$items = [];
3
4// Pre-sized array with values
5$numbers = array_fill(0, 5, 0); // [0, 0, 0, 0, 0]
6
7// Range of values
8$range = range(1, 10); // [1, 2, 3, ..., 10]
9$letters = range('a', 'z'); // ['a', 'b', ..., 'z']
10
11// Array from variables
12$name = 'John';
13$age = 30;
14$user = compact('name', 'age'); // ['name' => 'John', 'age' => 30]Spread Operator (PHP 7.4+):
1$array1 = [1, 2, 3];
2$array2 = [4, 5, 6];
3
4// Merge arrays
5$combined = [...$array1, ...$array2]; // [1, 2, 3, 4, 5, 6]
6
7// Add elements while spreading
8$extended = [0, ...$array1, 3.5, ...$array2, 7];
9// [0, 1, 2, 3, 3.5, 4, 5, 6, 7]Array Properties:
1$colors = ['red', 'green', 'blue'];
2
3// Count elements
4$count = count($colors); // 3
5
6// Check if empty
7$is_empty = empty($colors); // false
8
9// Check if key exists
10$has_red = in_array('red', $colors); // true
11$has_index = isset($colors[1]); // true
12$has_key = array_key_exists('name', $user); // booleanType Checking:
1$data = ['a', 'b', 'c'];
2
3is_array($data); // true
4
5// Check if array is a list (sequential numeric keys from 0)
6array_is_list($data); // true (PHP 8.1+)PHP provides multiple ways to iterate over arrays, each optimized for different scenarios and coding styles.
Foreach Loop (Most Common):
1$colors = ['red', 'green', 'blue'];
2
3// Iterate over values
4foreach ($colors as $color) {
5 echo "$color\n";
6}
7
8// Iterate over keys and values
9$user = ['name' => 'John', 'age' => 30];
10
11foreach ($user as $key => $value) {
12 echo "$key: $value\n";
13}Modifying Arrays During Iteration:
1$numbers = [1, 2, 3, 4, 5];
2
3// Modify by reference
4foreach ($numbers as &$number) {
5 $number *= 2;
6}
7unset($number); // Important: break reference
8
9print_r($numbers); // [2, 4, 6, 8, 10]For Loop (When Index Matters):
1$items = ['a', 'b', 'c', 'd'];
2
3for ($i = 0; $i < count($items); $i++) {
4 echo "$i: {$items[$i]}\n";
5}
6
7// Reverse iteration
8for ($i = count($items) - 1; $i >= 0; $i--) {
9 echo $items[$i];
10}While Loop with Array Functions:
1$queue = ['task1', 'task2', 'task3'];
2
3while ($task = array_shift($queue)) {
4 echo "Processing: $task\n";
5}Array Destructuring:
1// List destructuring
2[$first, $second, $third] = ['a', 'b', 'c'];
3echo $first; // "a"
4
5// Skip elements
6[$first, , $third] = ['a', 'b', 'c'];
7
8// Associative array destructuring
9['name' => $name, 'age' => $age] = [
10 'name' => 'John',
11 'age' => 30
12];
13
14// In foreach
15$users = [
16 ['name' => 'John', 'age' => 30],
17 ['name' => 'Jane', 'age' => 25]
18];
19
20foreach ($users as ['name' => $name, 'age' => $age]) {
21 echo "$name is $age years old\n";
22}Array Pointers (Legacy):
1$array = ['a', 'b', 'c'];
2
3// Current element
4current($array); // "a"
5
6// Move pointer
7next($array); // "b"
8prev($array); // "a"
9
10// Jump to end/start
11end($array); // "c"
12reset($array); // "a"
13
14// Get current key
15key($array); // 0PHP provides over 75 array functions. Mastering the essential ones will dramatically improve your code quality and efficiency.
array_map() - Transform Elements:
Apply a function to every element:
1$numbers = [1, 2, 3, 4, 5];
2
3// Square each number
4$squared = array_map(fn($n) => $n * $n, $numbers);
5// [1, 4, 9, 16, 25]
6
7// Multiple arrays
8$first_names = ['John', 'Jane'];
9$last_names = ['Doe', 'Smith'];
10
11$full_names = array_map(
12 fn($first, $last) => "$first $last",
13 $first_names,
14 $last_names
15);
16// ['John Doe', 'Jane Smith']array_filter() - Select Elements:
Keep only elements that match a condition:
1$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2
3// Even numbers only
4$even = array_filter($numbers, fn($n) => $n % 2 === 0);
5// [2, 4, 6, 8, 10]
6
7// Filter with keys
8$users = [
9 'john' => ['age' => 30, 'active' => true],
10 'jane' => ['age' => 17, 'active' => true],
11 'bob' => ['age' => 25, 'active' => false]
12];
13
14$active_adults = array_filter(
15 $users,
16 fn($user) => $user['active'] && $user['age'] >= 18
17);array_reduce() - Reduce to Single Value:
Combine all elements into one value:
1$numbers = [1, 2, 3, 4, 5];
2
3// Sum all numbers
4$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
5// 15
6
7// Product of all numbers
8$product = array_reduce($numbers, fn($carry, $n) => $carry * $n, 1);
9// 120
10
11// Concatenate strings
12$words = ['Hello', 'World', 'from', 'PHP'];
13$sentence = array_reduce(
14 $words,
15 fn($carry, $word) => $carry . ' ' . $word,
16 ''
17);
18// " Hello World from PHP"array_walk() - Modify Array In-Place:
1$products = [
2 ['name' => 'Laptop', 'price' => 999],
3 ['name' => 'Mouse', 'price' => 29]
4];
5
6// Add 8% tax to all products
7array_walk($products, function(&$product) {
8 $product['price'] *= 1.08;
9});array_column() - Extract Column:
Extract a single column from multi-dimensional array:
1$users = [
2 ['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
3 ['id' => 2, 'name' => 'Jane', 'email' => '[email protected]']
4];
5
6// Extract names
7$names = array_column($users, 'name');
8// ['John', 'Jane']
9
10// Extract with keys
11$users_by_id = array_column($users, null, 'id');
12// [1 => [...], 2 => [...]]Array Combination Functions:
1// Merge arrays
2$array1 = [1, 2, 3];
3$array2 = [4, 5, 6];
4$merged = array_merge($array1, $array2); // [1, 2, 3, 4, 5, 6]
5
6// Combine keys and values
7$keys = ['name', 'age', 'city'];
8$values = ['John', 30, 'NYC'];
9$user = array_combine($keys, $values);
10// ['name' => 'John', 'age' => 30, 'city' => 'NYC']
11
12// Unique values
13$numbers = [1, 2, 2, 3, 3, 3, 4];
14$unique = array_unique($numbers); // [1, 2, 3, 4]
15
16// Array difference
17$all = [1, 2, 3, 4, 5];
18$excluded = [2, 4];
19$result = array_diff($all, $excluded); // [1, 3, 5]
20
21// Array intersection
22$array1 = [1, 2, 3, 4];
23$array2 = [3, 4, 5, 6];
24$common = array_intersect($array1, $array2); // [3, 4]Array Searching:
1$colors = ['red', 'green', 'blue'];
2
3// Find value
4in_array('green', $colors); // true
5
6// Find key
7$key = array_search('blue', $colors); // 2
8
9// Find with callback
10$users = [
11 ['id' => 1, 'name' => 'John'],
12 ['id' => 2, 'name' => 'Jane']
13];
14
15$user = array_find($users, fn($u) => $u['id'] === 2); // PHP 8.4+Sorting is one of the most common array operations. PHP provides numerous sorting functions for different scenarios.
Basic Sorting:
1$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
2
3// Sort ascending (modifies original)
4sort($numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
5
6// Sort descending
7rsort($numbers); // [9, 6, 5, 4, 3, 2, 1, 1]
8
9// Maintain key association
10$prices = ['apple' => 3, 'banana' => 2, 'cherry' => 5];
11asort($prices); // ['banana' => 2, 'apple' => 3, 'cherry' => 5]
12arsort($prices); // DescendingSort by Keys:
1$user = [
2 'email' => '[email protected]',
3 'name' => 'John',
4 'age' => 30
5];
6
7// Sort by keys
8ksort($user); // ['age' => 30, 'email' => ..., 'name' => ...]
9krsort($user); // ReverseCustom Sorting with usort():
1$users = [
2 ['name' => 'John', 'age' => 30],
3 ['name' => 'Jane', 'age' => 25],
4 ['name' => 'Bob', 'age' => 35]
5];
6
7// Sort by age
8usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
9
10// Sort by name (descending)
11usort($users, fn($a, $b) => $b['name'] <=> $a['name']);
12
13// Multi-criteria sort
14usort($users, function($a, $b) {
15 // First by age, then by name
16 $age_cmp = $a['age'] <=> $b['age'];
17 return $age_cmp !== 0 ? $age_cmp : $a['name'] <=> $b['name'];
18});Natural and Case-Insensitive Sorting:
1$files = ['file10.txt', 'file2.txt', 'file1.txt'];
2
3// Regular sort
4sort($files); // ['file1.txt', 'file10.txt', 'file2.txt']
5
6// Natural sort (handles numbers correctly)
7natsort($files); // ['file1.txt', 'file2.txt', 'file10.txt']
8
9// Case-insensitive natural sort
10natcasesort($files);Shuffle and Reverse:
1$deck = ['A', 'K', 'Q', 'J'];
2
3// Shuffle randomly
4shuffle($deck);
5
6// Reverse order
7$reversed = array_reverse($deck);
8
9// Reverse with keys
10$reversed_with_keys = array_reverse($deck, true);Array Slicing and Splicing:
1$items = ['a', 'b', 'c', 'd', 'e'];
2
3// Extract portion
4$slice = array_slice($items, 1, 3); // ['b', 'c', 'd']
5$last_two = array_slice($items, -2); // ['d', 'e']
6
7// Remove and replace
8$removed = array_splice($items, 1, 2, ['x', 'y']);
9// $items is now ['a', 'x', 'y', 'd', 'e']
10// $removed is ['b', 'c']Array Chunking:
1$items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
2
3// Split into chunks of 3
4$chunks = array_chunk($items, 3);
5// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
6
7// Preserve keys
8$chunks = array_chunk($items, 3, true);Stack and Queue Operations:
1$stack = [];
2
3// Push (add to end)
4array_push($stack, 'a', 'b', 'c');
5
6// Pop (remove from end)
7$last = array_pop($stack); // 'c'
8
9// Unshift (add to beginning)
10array_unshift($stack, 'z');
11
12// Shift (remove from beginning)
13$first = array_shift($stack); // 'z'Building a Data Processing Pipeline
1<?php
2declare(strict_types=1);
3
4/**
5 * E-Commerce Data Processing System
6 *
7 * Demonstrates comprehensive array manipulation:
8 * - Multi-dimensional array processing
9 * - Filtering, mapping, and reducing
10 * - Sorting and grouping
11 * - Complex data transformations
12 */
13
14// Sample product data
15$products = [
16 ['id' => 1, 'name' => 'Laptop', 'price' => 999, 'category' => 'Electronics', 'stock' => 5],
17 ['id' => 2, 'name' => 'Mouse', 'price' => 29, 'category' => 'Electronics', 'stock' => 50],
18 ['id' => 3, 'name' => 'Desk', 'price' => 299, 'category' => 'Furniture', 'stock' => 0],
19 ['id' => 4, 'name' => 'Chair', 'price' => 199, 'category' => 'Furniture', 'stock' => 12],
20 ['id' => 5, 'name' => 'Monitor', 'price' => 399, 'category' => 'Electronics', 'stock' => 8],
21 ['id' => 6, 'name' => 'Keyboard', 'price' => 79, 'category' => 'Electronics', 'stock' => 25],
22 ['id' => 7, 'name' => 'Bookshelf', 'price' => 149, 'category' => 'Furniture', 'stock' => 3],
23];
24
25echo "🛍️ E-COMMERCE DATA PROCESSING\n";
26echo str_repeat("=", 60) . "\n\n";
27
28// 1. Filter in-stock products
29echo "1. In-Stock Products:\n";
30$in_stock = array_filter($products, fn($p) => $p['stock'] > 0);
31echo " Found: " . count($in_stock) . " products\n";
32
33// 2. Group by category
34echo "\n2. Products by Category:\n";
35$by_category = [];
36foreach ($products as $product) {
37 $by_category[$product['category']][] = $product;
38}
39
40foreach ($by_category as $category => $items) {
41 echo " $category: " . count($items) . " products\n";
42}
43
44// 3. Calculate statistics
45echo "\n3. Price Statistics:\n";
46$prices = array_column($products, 'price');
47$total_value = array_sum(array_map(
48 fn($p) => $p['price'] * $p['stock'],
49 $products
50));
51
52echo " Min Price: $" . number_format(min($prices), 2) . "\n";
53echo " Max Price: $" . number_format(max($prices), 2) . "\n";
54echo " Avg Price: $" . number_format(array_sum($prices) / count($prices), 2) . "\n";
55echo " Total Inventory Value: $" . number_format($total_value, 2) . "\n";
56
57// 4. Top 3 most expensive products
58echo "\n4. Top 3 Most Expensive:\n";
59$sorted = $products;
60usort($sorted, fn($a, $b) => $b['price'] <=> $a['price']);
61$top_3 = array_slice($sorted, 0, 3);
62
63foreach ($top_3 as $product) {
64 echo " {$product['name']}: $" . number_format($product['price'], 2) . "\n";
65}
66
67// 5. Apply discount to electronics
68echo "\n5. Electronics with 10% Discount:\n";
69$electronics = array_filter($products, fn($p) => $p['category'] === 'Electronics');
70$discounted = array_map(function($p) {
71 $original = $p['price'];
72 $discounted = $original * 0.9;
73 return [
74 'name' => $p['name'],
75 'original' => $original,
76 'sale' => $discounted,
77 'savings' => $original - $discounted
78 ];
79}, $electronics);
80
81foreach ($discounted as $item) {
82 echo sprintf(
83 " %s: $%.2f → $%.2f (save $%.2f)\n",
84 $item['name'],
85 $item['original'],
86 $item['sale'],
87 $item['savings']
88 );
89}
90
91// 6. Low stock alert
92echo "\n6. Low Stock Alert (< 10 items):\n";
93$low_stock = array_filter($in_stock, fn($p) => $p['stock'] < 10);
94usort($low_stock, fn($a, $b) => $a['stock'] <=> $b['stock']);
95
96foreach ($low_stock as $product) {
97 echo " ⚠️ {$product['name']}: {$product['stock']} remaining\n";
98}
99
100// 7. Create product summary
101echo "\n7. Product Summary:\n";
102$summary = array_map(
103 fn($p) => "{$p['name']} ({$p['category']}) - \${$p['price']}",
104 $products
105);
106
107foreach ($summary as $line) {
108 echo " • $line\n";
109}
110
111// 8. Find most stocked category
112echo "\n8. Category with Most Stock:\n";
113$category_stock = array_reduce($products, function($carry, $product) {
114 $category = $product['category'];
115 if (!isset($carry[$category])) {
116 $carry[$category] = 0;
117 }
118 $carry[$category] += $product['stock'];
119 return $carry;
120}, []);
121
122arsort($category_stock);
123[$top_category, $stock_count] = array_slice($category_stock, 0, 1, true);
124echo " $top_category: $stock_count items\n";
125
126echo "\n" . str_repeat("=", 60) . "\n";
127echo "✅ Processing Complete!\n";
128?>This example demonstrates professional array manipulation:
Data Filtering:
array_filter() to select products meeting criteriaData Transformation:
array_map() to apply discounts and format dataarray_column() to extract specific fieldsAggregation:
array_reduce() to accumulate category totalsarray_sum() for price calculationsSorting and Ranking:
usort() with spaceship operator for custom sortingarray_slice() to get top N itemsGrouping and Categorization:
Practical Patterns:
Performance Considerations:
Code Quality:
$low_stock, $by_category)Your progress is saved in this browser, on this device only.