An array holds many values under one name. In PHP an array is an ordered map: every value has a key, and the order you add items is kept. That single structure works as a list, a dictionary or a stack.
Indexed arrays
When you do not give keys, PHP numbers the items from 0:
<?php
$languages = ['PHP', 'JavaScript', 'Python'];
echo $languages[0]; // PHP
echo $languages[2]; // Python
echo count($languages); // 3
Indexes start at 0, so the last item of an array with three elements is at index 2. Trying to read $languages[3] gives a warning and null.
Associative arrays
Give each value a meaningful key when position does not mean anything:
<?php
$user = [
'name' => 'Asha',
'email' => 'asha@example.com',
'posts' => 42,
];
echo $user['name']; // Asha
echo "{$user['name']} has written {$user['posts']} posts.";
Keys can be strings or integers. Values can be anything, including other arrays.
Adding, updating and removing
<?php
$cart = ['apple', 'bread'];
$cart[] = 'milk'; // Append: ['apple', 'bread', 'milk']
$cart[0] = 'green apple'; // Update by index
$user = ['name' => 'Asha'];
$user['role'] = 'editor'; // Add a new key
unset($user['role']); // Remove a key
array_pop($cart); // Remove and return the last item ('milk')
array_unshift($cart, 'eggs'); // Add to the start
Reading safely
Reading a key that does not exist raises a warning. Check first, or supply a default:
<?php
$settings = ['theme' => 'dark'];
$theme = $settings['theme'] ?? 'light'; // 'dark'
$language = $settings['language'] ?? 'en'; // 'en', no warning
var_dump(array_key_exists('theme', $settings)); // true
var_dump(isset($settings['language'])); // false
var_dump(in_array('dark', $settings, true)); // true: searches values
Pass true as the third argument of in_array() to compare strictly. Without it, in_array('1e1', ['10']) returns true.
isset() returns false for keys whose value is null; array_key_exists() returns true for them. Use array_key_exists() when null is a meaningful value.
Nested arrays
Arrays can contain arrays, which is how you represent lists of records:
<?php
$products = [
['name' => 'Notebook', 'price' => 3.50, 'stock' => 12],
['name' => 'Pen', 'price' => 1.20, 'stock' => 0],
['name' => 'Backpack', 'price' => 24.00, 'stock' => 3],
];
echo $products[2]['name']; // Backpack
foreach ($products as $product) {
$status = $product['stock'] > 0 ? 'in stock' : 'sold out';
echo "{$product['name']}: {$status}", PHP_EOL;
}
Sorting
Sorting functions change the array in place:
| Function | Sorts by | Keeps keys? |
|---|---|---|
sort / rsort | Value, ascending / descending | No, re-indexes |
asort / arsort | Value | Yes |
ksort / krsort | Key | Yes |
usort | Your own comparison | No |
<?php
$scores = ['Ben' => 72, 'Ada' => 91, 'Cy' => 85];
arsort($scores);
print_r($scores); // Ada 91, Cy 85, Ben 72
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);
echo $products[0]['name']; // Pen (cheapest first)
The spaceship operator <=> returns -1, 0 or 1, exactly what usort expects.
Transforming arrays
These functions return a new array and leave the original unchanged:
<?php
$prices = [10, 25, 40];
$withVat = array_map(fn($p) => $p * 1.2, $prices); // [12, 30, 48]
$expensive = array_filter($prices, fn($p) => $p > 20); // [1 => 25, 2 => 40]
$total = array_sum($prices); // 75
$names = array_column($products, 'name'); // ['Pen', 'Notebook', 'Backpack']
fn($p) => ... is an arrow function: a short, one-expression function. You will meet functions properly in the next lesson.
array_filter() keeps the original keys, so the result above starts at key 1. Wrap it in array_values() when you need a clean 0, 1, 2 list.
Unpacking
Pull values out into variables in one step:
<?php
[$first, $second] = ['PHP', 'JavaScript'];
['name' => $name, 'email' => $email] = $user;
$all = [...$languages, 'Go']; // Spread one array into another
Summary
- PHP arrays are ordered maps: indexed (keys 0, 1, 2) or associative (named keys).
- Append with
$array[] = value, remove withunset()orarray_pop(). - Read optional keys with
??; check witharray_key_exists(),isset()orin_array(..., true). - Sort in place with
sort,asort,ksortorusort. - Transform with
array_map,array_filter,array_sumandarray_column.