One variable, many values
A shop has many products, an order has many lines, a form has many fields. Storing each in a separate variable does not scale. An array holds any number of values in one variable, each stored under a key. PHP arrays are flexible: the same type serves as a list, a dictionary and a table row.
Indexed arrays
An indexed array is a plain list. Write it with square brackets. PHP numbers the elements automatically, starting at 0:
<?php
$products = ["Mechanical Keyboard", "Ceramic Mug Set", "Water Bottle"];
echo $products[0] . "\n";
echo $products[2] . "\n";
echo "There are " . count($products) . " products\n";Mechanical Keyboard
Water Bottle
There are 3 productsThe first element is $products[0] and the last is $products[count($products) - 1]. Counting from zero takes a little getting used to, but it is the same in almost every programming language. You may also see the older syntax array("a", "b"); it means exactly the same as ["a", "b"].
Associative arrays
An associative array uses keys you choose, usually strings, with => between key and value. It describes one thing with named fields:
<?php
$product = [
"name" => "Yoga Mat",
"price" => 24.99,
"stock" => 80,
"category" => "Sports",
];
echo $product["name"] . " costs " . $product["price"] . "\n";
echo "In stock: {$product['stock']}\n";Yoga Mat costs 24.99
In stock: 80Each key is unique. Keys can be integers or strings; a string that looks like a whole number, such as "5", becomes the integer key 5. Values can be anything, including other arrays, which is the subject of Multidimensional arrays.
Adding and changing elements
Assign to a key to add or replace it. Empty brackets, [], append to the end with the next free integer key:
<?php
$cart = ["Mug"];
$cart[] = "Keyboard";
$cart[] = "Bottle";
$cart[0] = "Mug Set"; // replace the first element
$product = ["name" => "Desk Mat"];
$product["price"] = 55; // add a new key
$product["name"] = "Standing Desk Mat"; // replace a value
print_r($cart);
print_r($product);Array
(
[0] => Mug Set
[1] => Keyboard
[2] => Bottle
)
Array
(
[name] => Standing Desk Mat
[price] => 55
)array_unshift() adds to the start, array_push() to the end (same as []), and array_pop() and array_shift() remove and return the last and first elements.
Removing elements
unset() removes a key and its value. In an indexed array this leaves a gap: the other keys are not renumbered. array_values() renumbers them when you need a clean list:
<?php
$queue = ["Asha", "Farid", "Kavya", "Liam"];
unset($queue[1]);
print_r($queue);
print_r(array_values($queue));Array
(
[0] => Asha
[2] => Kavya
[3] => Liam
)
Array
(
[0] => Asha
[1] => Kavya
[2] => Liam
)Checking for keys and values
Reading a key that does not exist raises a warning, just like an undefined variable:
<?php
$product = ["name" => "Yoga Mat", "price" => 24.99];
echo "Colour: " . $product["colour"] . "\n";
echo "Colour: " . ($product["colour"] ?? "not set") . "\n";Warning: Undefined array key "colour" in /path/to/script.php on line 3
Colour:
Colour: not setSo check first, or use ?? as in the null coalescing lesson. There are two ways to ask whether a key exists, and they differ for null values:
<?php
$user = ["name" => "Asha", "phone" => null];
var_dump(isset($user["phone"]));
var_dump(array_key_exists("phone", $user));
var_dump(isset($user["email"]));
var_dump(in_array("Asha", $user, true));bool(false)
bool(true)
bool(false)
bool(true)isset() answers "is there a non-null value?", while array_key_exists() answers "is the key there at all?". in_array() searches the values; pass true as the third argument for strict comparison.
Unpacking into variables
Square brackets on the left of = unpack an array into variables. For associative arrays, name the keys:
<?php
[$first, $second] = ["Gold", "Silver", "Bronze"];
echo "$first, $second\n";
["name" => $name, "price" => $price] = ["name" => "Water Bottle", "price" => 12];
echo "$name: $price\n";
[, , $third] = ["Gold", "Silver", "Bronze"];
echo "$third\n";Gold, Silver
Water Bottle: 12
BronzeLeaving a position empty skips it. You saw this in loops already: foreach ($rows as [$name, $price]).
Combining arrays
The spread operator ... merges arrays, and + combines them by key, keeping the left side's values when keys clash:
<?php
$fruit = ["apple", "pear"];
$veg = ["carrot"];
print_r([...$fruit, ...$veg]);
$defaults = ["currency" => "INR", "perPage" => 20];
$chosen = ["perPage" => 50];
print_r($chosen + $defaults);Array
(
[0] => apple
[1] => pear
[2] => carrot
)
Array
(
[perPage] => 50
[currency] => INR
)The $chosen + $defaults pattern fills in missing settings without overwriting the ones that were chosen. array_merge(), covered in Common array functions, behaves differently for numeric keys.
Common mistakes
- Starting to count at 1. The first element of a list is
[0]. - Reading a key that may be missing without
??orisset(). - Expecting unset() to renumber a list. Use
array_values(). - Using isset() to check for a key whose value may be null. Use
array_key_exists().
Exercise
Create an associative array for a customer with keys first_name (Farid), last_name (Khan), city (Mumbai) and phone (null). Print the full name, change the city to Pune, add an email of farid@example.com, remove phone, and print the final array with print_r.
Show one possible answer
<?php
$customer = ["first_name" => "Farid", "last_name" => "Khan", "city" => "Mumbai", "phone" => null];
echo $customer["first_name"] . " " . $customer["last_name"] . "\n";
$customer["city"] = "Pune";
$customer["email"] = "farid@example.com";
unset($customer["phone"]);
print_r($customer);Farid Khan
Array
(
[first_name] => Farid
[last_name] => Khan
[city] => Pune
[email] => farid@example.com
)Key points
- An array stores many values under keys. Indexed arrays use 0, 1, 2...; associative arrays use your own string keys.
- $list[] = $value appends; $map['key'] = $value sets or replaces; unset($map['key']) removes.
- isset($a['k']) is false for a null value; array_key_exists('k', $a) is true whenever the key exists.
- Reading a missing key raises a warning, so use ?? or check first.