PHP Arrays — Indexed, Associative, Multidimensional, and Array Functions
In this tutorial, you will learn about PHP Arrays. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP arrays are ordered maps that can function as indexed lists, associative dictionaries, or multidimensional structures, making them the most versatile and frequently used data type in PHP applications.
Why It Matters
Arrays are everywhere in PHP. Database results come as arrays of rows. Form submissions arrive as $_POST arrays. JSON API responses are arrays. Session data is stored in $_SESSION arrays. PHP provides over 80 built-in array functions, and knowing the right one saves hours of manual coding. Understanding how PHP arrays work internally -- they are actually hash maps -- explains why certain operations are fast and others are slow.
Real-World Use
WordPress stores post metadata in associative arrays. Laravel's collections wrap arrays with convenient methods. E-commerce applications keep cart items in arrays with product IDs as keys. Configuration files return arrays. Every JSON API response is serialized from a PHP array. DodaTech's dashboard arrays log entries, user settings, and scan results using arrays extensively.
What You Will Learn
- Indexed and associative array syntax
- Multidimensional arrays and array traversal
- Array operations: push, pop, shift, unshift, merge, diff, intersect
- Array functions: map, filter, reduce, sort, search
- Array destructuring and spread operator
- Performance considerations and SplFixedArray
Learning Path
flowchart LR A[Functions] --> B[Arrays
You are here] B --> C[Superglobals] C --> D[Forms] D --> E[Sessions] style B fill:#f90,color:#fff
Indexed Arrays
Indexed arrays use numeric keys starting from 0:
<?php
// Old syntax
$colors = array('Red', 'Green', 'Blue');
// Short syntax (preferred)
$colors = ['Red', 'Green', 'Blue'];
echo $colors[0]; // Red
echo $colors[2]; // Blue
// Add elements
$colors[] = 'Yellow'; // Appends at index 3
print_r($colors);
Expected output:
Array
(
[0] => Red
[1] => Green
[2] => Blue
[3] => Yellow
)
PHP arrays are dynamic. You do not need to declare a size. Adding an element with $array[] = value appends it at the next available integer key.
Associative Arrays
Associative arrays use named string keys:
<?php
$user = [
'name' => 'Alice Johnson',
'email' => 'alice@example.com',
'role' => 'admin',
'age' => 30,
];
echo $user['name']; // Alice Johnson
echo $user['email']; // alice@example.com
// Modify a value
$user['role'] = 'editor';
// Add a new key
$user['active'] = true;
print_r($user);
Expected output:
Array
(
[name] => Alice Johnson
[email] => alice@example.com
[role] => editor
[age] => 30
[active] => 1
)
Multidimensional Arrays
Arrays can contain other arrays, creating multi-level structures:
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 999.99],
['id' => 2, 'name' => 'Mouse', 'price' => 29.99],
['id' => 3, 'name' => 'Keyboard', 'price' => 79.99],
];
// Access nested values
echo $products[0]['name']; // Laptop
echo $products[1]['price']; // 29.99
// Iterate through all products
foreach ($products as $product) {
echo "{$product['name']}: \${$product['price']}\n";
}
Expected output:
Laptop: $999.99
Mouse: $29.99
Keyboard: $79.99
Array Operations
Adding and Removing Elements
<?php
$stack = [1, 2, 3];
array_push($stack, 4, 5); // [1, 2, 3, 4, 5]
$last = array_pop($stack); // Removes 5, stack is [1, 2, 3, 4]
$first = array_shift($stack); // Removes 1, stack is [2, 3, 4]
array_unshift($stack, 0); // [0, 2, 3, 4]
print_r($stack);
Expected output:
Array
(
[0] => 0
[1] => 2
[2] => 3
[3] => 4
)
Merging and Diffing
<?php
$a = [1, 2, 3];
$b = [3, 4, 5];
$merged = array_merge($a, $b); // [1, 2, 3, 3, 4, 5]
$unique = array_unique($merged); // [1, 2, 3, 4, 5]
$diff = array_diff($a, $b); // [1, 2] (in a but not b)
$intersect = array_intersect($a, $b); // [3]
print_r($diff);
print_r($intersect);
Expected output:
Array
(
[0] => 1
[1] => 2
)
Array
(
[2] => 3
)
Array Functions: Map, Filter, Reduce
PHP provides Functional Programming patterns through array functions:
<?php
$numbers = [1, 2, 3, 4, 5, 6];
// array_map: transform each element
$squared = array_map(fn($n) => $n * $n, $numbers);
print_r($squared);
// array_filter: keep elements matching a condition
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even);
// array_reduce: reduce to a single value
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
echo "Sum: $sum\n";
Expected output:
Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
[5] => 36
)
Array
(
[1] => 2
[3] => 4
[5] => 6
)
Sum: 21
Note that array_filter preserves keys. Use array_values() to re-index numerically.
Sorting Arrays
PHP offers many sorting functions that modify the original array:
<?php
$fruits = ['banana', 'apple', 'Cherry', 'date'];
sort($fruits); // Ascending by value, re-indexes
print_r($fruits);
$ages = ['Alice' => 30, 'Bob' => 25, 'Charlie' => 35];
asort($ages); // Ascending by value, preserves keys
print_r($ages);
ksort($ages); // Ascending by key
print_r($ages);
Expected output:
Array
(
[0] => Cherry
[1] => apple
[2] => banana
[3] => date
)
Array
(
[Bob] => 25
[Alice] => 30
[Charlie] => 35
)
Array
(
[Alice] => 30
[Bob] => 25
[Charlie] => 35
)
Sort functions compare strings case-sensitively by default. Use SORT_FLAG_CASE or strcasecmp for case-insensitive sorting.
Array Destructuring
PHP 7.1 introduced symmetric array destructuring:
<?php
$array = [1, 2, 3];
[$a, $b, $c] = $array;
echo "$a, $b, $c"; // 1, 2, 3
// Skip elements with commas
[$first, , $third] = $array;
echo "$first, $third"; // 1, 3
// Associative destructuring
$user = ['name' => 'Alice', 'age' => 30];
['name' => $name, 'age' => $age] = $user;
echo "$name is $age"; // Alice is 30
Spread Operator in Arrays
PHP 7.4 introduced the spread operator for arrays:
<?php
$first = [1, 2, 3];
$second = [4, 5, 6];
$combined = [...$first, ...$second];
print_r($combined); // [1, 2, 3, 4, 5, 6]
// With additional elements
$result = [0, ...$first, 10, ...$second];
print_r($result); // [0, 1, 2, 3, 10, 4, 5, 6]
Common Mistakes
1. Confusing isset and array_key_exists
$arr = ['a' => 1, 'b' => null];
isset($arr['b']); // false (value is null)
array_key_exists('b', $arr); // true (key exists)
2. Modifying an Array While Iterating
foreach ($array as $key => $value) {
if ($value === 'remove') {
unset($array[$key]); // Can cause skipped elements
}
}
Use array_filter instead, or collect keys to remove in a separate array.
3. Using Loose Comparison in in_array
in_array('1e0', [1, 2, 3]); // true (loose comparison)
in_array('1e0', [1, 2, 3], true); // false (strict)
Always pass true as the third argument for strict comparison.
4. Assuming array_merge Preserves Keys for Numeric Keys
$a = [1, 2];
$b = [3, 4];
array_merge($a, $b); // [1, 2, 3, 4] - re-indexed
Use + for union: $a + $b preserves keys from the first array.
5. Not Checking If a Key Exists
echo $_GET['user']; // Warning if key does not exist
Use $_GET['user'] ?? 'default' or isset() to check first.
Practice Questions
What is the difference between indexed and associative arrays? Indexed arrays use numeric keys starting at 0. Associative arrays use named string keys.
How do you remove the last element of an array? Use
array_pop($array). It returns the removed element and modifies the original array.What does array_map do? It applies a callback function to each element and returns a new array with the transformed values.
How do you check if a key exists in an array? Use
array_key_exists('key', $array)orisset($array['key'])(which returns false for null values).Challenge: Write a function that receives an array of products with name and price, filters out products under $10, sorts by price descending, and returns the top 3 most expensive.
Mini Project: Shopping Cart
Implement a simple shopping cart using arrays:
<?php
$cart = [];
function addItem(array &$cart, int $id, string $name, float $price, int $qty = 1): void {
if (isset($cart[$id])) {
$cart[$id]['qty'] += $qty;
} else {
$cart[$id] = ['name' => $name, 'price' => $price, 'qty' => $qty];
}
}
function removeItem(array &$cart, int $id): void {
unset($cart[$id]);
}
function calculateTotal(array $cart): float {
$total = 0;
foreach ($cart as $item) {
$total += $item['price'] * $item['qty'];
}
return $total;
}
addItem($cart, 1, 'Laptop', 999.99);
addItem($cart, 2, 'Mouse', 29.99, 2);
addItem($cart, 1, 'Laptop', 999.99); // Increase qty
removeItem($cart, 2);
echo "Cart items: " . count($cart) . "\n";
echo "Total: $" . number_format(calculateTotal($cart), 2) . "\n";
print_r($cart);
FAQ
What is Next
Now that you understand arrays, proceed to Superglobals to learn about PHP's predefined variables for accessing form data, server information, and environment variables. Then read Forms to build your first interactive web forms.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro