PHP Arrays

Store lists and labelled data in indexed and associative arrays, and use PHP's array functions.

Lesson 6 of 86Beginner17 min read

An array stores many values in a single variable. PHP arrays are very flexible: the same structure works as a simple numbered list, as a set of labelled values, or as a table made of rows.

An indexed array numbers its items from 0, like a shopping list. An associative array gives each item a key that you choose, such as "name" or "price", like the fields of a form. Nest them together and you can represent a whole list of products, each with its own name, price and stock.

Arrays are at the heart of almost every PHP page: database results, form data and settings all arrive as arrays. In this lesson you'll create, change, search, sort and loop through them.

Indexed arrays

PHP
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0];         // apple
$fruits[] = "date";      // add to the end
echo count($fruits);     // 4
  • Items are numbered from 0.
  • $array[] = value adds an item to the end. array_push($fruits, "elder") does the same.
  • count() returns how many items there are.
  • array_pop() removes and returns the last item.

Associative arrays

Use key => value pairs to label each item:

PHP
$product = [
    "name" => "Desk lamp",
    "price" => 24.50,
    "stock" => 22,
];

echo $product["name"];   // Desk lamp
$product["stock"] = 21;  // change a value
$product["colour"] = "black";  // add a new key

Keys are usually strings. Use isset($product["colour"]) or array_key_exists() to check whether a key exists before reading it. The trailing comma after the last item is allowed, and makes adding new lines easier.

Arrays of arrays

Put associative arrays inside an indexed array to build a list of records, just like rows from a database table:

PHP
$products = [
    ["name" => "Pen", "price" => 1.20],
    ["name" => "Notebook", "price" => 3.50],
];
echo $products[1]["name"];   // Notebook

Read it from left to right: item 1 of the list, then its "name" key.

Adding and removing items

PHP has a function for each end of a list, plus tools for the middle:

TaskFunctionExample result for ["b", "c"]
Add to the end$a[] = "d" or array_push($a, "d")["b", "c", "d"]
Add to the startarray_unshift($a, "a")["a", "b", "c"]
Remove the last itemarray_pop($a)returns "c"
Remove the first itemarray_shift($a)returns "b"
Remove by keyunset($a[0])[1 => "c"]
Remove and insert in the middlearray_splice($a, 1, 1, ["x"])["b", "x"]

Note how unset() leaves a gap: removing key 1 from [3, 1, 2] leaves keys 0 and 2. That's fine for associative arrays, but for lists, call array_values() afterwards to renumber the items from 0.

Arrays are copied when assigned

Assigning an array to another variable makes an independent copy:

PHP
$original = [1, 2];
$copy = $original;
$copy[] = 3;
echo count($original);   // 2
echo count($copy);       // 3

The same happens when you pass an array to a function: the function works on its own copy, so the caller's array doesn't change unless the parameter is declared by reference with &. PHP copies lazily, only when one of the arrays is actually changed, so passing large arrays around is still fast. Objects behave differently: assigning an object shares the same object, as the classes lesson explains.

Useful array functions

FunctionWhat it does
in_array("pen", $a)Is the value in the array?
array_search("pen", $a)Key of the value, or false
sort($a) / rsort($a)Sort values up / down
ksort($a) / asort($a)Sort by key / by value, keeping keys
array_sum($a)Total of the values
implode(", ", $a)Join into a string
explode(",", $s)Split a string into an array

sort() changes the array in place and renumbers it. For associative arrays, use asort() or ksort() so the keys stay attached to their values.

PHP Arrays Syntax

Arrays

$list = ["a", "b", "c"];
$list[] = "d";

$map = ["key" => "value", "other" => 2];
$map["key"];

$rows = [
    ["name" => "A", "qty" => 1],
    ["name" => "B", "qty" => 2],
];

foreach ($map as $key => $value) { }

PHP Arrays Summary

  • Indexed arrays: ["a", "b"], numbered from 0. Add with $a[] = ....
  • Associative arrays: ["key" => "value"], read with $a["key"].
  • Nest arrays to store lists of records.
  • count(), in_array(), sort(), array_sum(), implode() and explode() are everyday tools.
  • Loop with foreach ($a as $key => $value).

PHP Arrays Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A shopping list

PHP
<?php
$list = ["milk", "bread"];
$list[] = "eggs";
array_push($list, "honey");

echo "Items: " . count($list) . "\n";
echo "First: " . $list[0] . "\n";
echo "All: " . implode(", ", $list) . "\n";
echo in_array("bread", $list) ? "Bread is on the list" : "No bread";
Output
Items: 4
First: milk
All: milk, bread, eggs, honey
Bread is on the list
Line-by-line explanation
  1. Lines 3 to 4Two ways to add items to the end.
  2. Line 8implode() joins every item into one string with ", " between them.
  3. Line 9in_array() returns true, so the ternary picks the first message.
Example 2

A product record

PHP
<?php
$product = [
    "name" => "Water bottle",
    "price" => 12.00,
    "stock" => 40,
];

$product["stock"] -= 2;
$product["sale"] = true;

foreach ($product as $key => $value) {
    echo "$key: " . var_export($value, true) . "\n";
}
Output
name: 'Water bottle'
price: 12.0
stock: 38
sale: true
Line-by-line explanation
  1. Lines 2 to 6Each value has a named key.
  2. Line 8Change a value by its key.
  3. Line 9Assigning to a new key adds it.
  4. Lines 11 to 13foreach gives both the key and the value. var_export() prints values the way PHP code would write them.
Example 3

A table from an array of records

PHP
<?php
$orders = [
    ["item" => "Backpack", "qty" => 1, "price" => 34.99],
    ["item" => "Pen", "qty" => 10, "price" => 1.20],
    ["item" => "Notebook", "qty" => 5, "price" => 3.50],
];

$total = 0;
foreach ($orders as $o) {
    $line = $o["qty"] * $o["price"];
    $total += $line;
    echo str_pad($o["item"], 10) . number_format($line, 2) . "\n";
}
echo str_pad("Total", 10) . number_format($total, 2);
Output
Backpack  34.99
Pen       12.00
Notebook  17.50
Total     64.49
Line-by-line explanation
  1. Lines 2 to 6An indexed array where every item is an associative array.
  2. Line 10Read two keys from the current record and multiply them.
  3. Line 12str_pad() lines the names up; number_format() shows two decimals.

Common PHP Arrays Mistakes

Reading a key that doesn't exist

Don't
echo $user["email"];   // Warning: Undefined array key
Do
echo $user["email"] ?? "no email";

Using sort() on an associative array

Don't
$prices = ["pen" => 1.2, "lamp" => 24.5, "cup" => 8];
sort($prices);   // keys are lost: [0 => 1.2, 1 => 8, 2 => 24.5]
Do
$prices = ["pen" => 1.2, "lamp" => 24.5, "cup" => 8];
asort($prices);  // keeps keys: pen, cup, lamp

Echoing a whole array

Don't
$colours = ["red", "blue"];
echo $colours;   // Array, plus a warning
Do
$colours = ["red", "blue"];
echo implode(", ", $colours);

PHP Arrays in Real Projects

Arrays in PHP apps

Form submissions arrive in the $_POST associative array, the page address's query values arrive in $_GET, and database results come back as arrays of rows. A product page typically receives an array like $product above and prints $product["name"] and $product["price"] into the HTML template.

PHP Arrays FAQ

How do I check if a PHP array is empty?

Use empty($items) or count($items) === 0. Both return the expected result for []. empty() also returns true when the variable doesn't exist, without a warning, which is convenient for optional data but can hide a misspelled variable name.

What is the difference between isset and array_key_exists?

isset($a['k']) returns false when the key is missing or when its value is null. array_key_exists('k', $a) returns true whenever the key exists, even with a null value. Use array_key_exists when null is a meaningful stored value.

How do I remove an item by its value?

Find its key with array_search and unset it, or keep everything else with array_diff($a, ['b']) or array_filter. All of these keep the original keys, so wrap the result in array_values() if you need a clean list numbered from 0.

How do I get the last element of an array?

Use $a[array_key_last($a)], available since PHP 7.3, which works for both lists and associative arrays without changing anything. end($a) also returns the last value, but it moves the array's internal pointer, which can surprise later code.

Do PHP arrays keep their order?

Yes. PHP arrays remember the order in which items were added, for both numeric and string keys, and foreach visits them in that order. Sorting functions change the order deliberately, and ksort or asort keep keys attached to their values while doing so.

PHP Arrays Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so it prints Oslo.

$city = ["name" => "Oslo", "country" => "Norway"];
echo $city[""];
Predict the outputeasy

What does this print?

$n = [5, 10, 15];
$n[] = 20;
echo count($n);
Predict the outputmedium

What does this print?

$parts = explode("-", "2024-07-15");
echo $parts[1];
Multiple choicemedium

Which function sorts an associative array by value and keeps the keys?

Predict the outputmedium

What does this print?

$colours = ["red", "green"];
$colours[] = "blue";
echo count($colours) . " " . $colours[2];

PHP Arrays Quiz

5 questions to check what you learned.

  1. What is the index of the first item in a PHP indexed array?

    • 1
    • 0
    • "first"
    • -1
  2. Which function returns the number of items in an array?

    • count()
    • strlen()
    • size()
    • length()
  3. What does implode(" | ", ["a", "b", "c"]) return?

    • ["a | b | c"]
    • "abc"
    • "a | b | c"
    • "a b c"
  4. How do you read the price of the second product in $products, an array of associative arrays?

    • $products["price"][1]
    • $products[2]["price"]
    • $products->price[1]
    • $products[1]["price"]
  5. How do you read the value for the key "email" in $user?

    • $user.email
    • $user->email
    • $user(email)
    • $user["email"]