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
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // apple
$fruits[] = "date"; // add to the end
echo count($fruits); // 4- Items are numbered from 0.
$array[] = valueadds 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:
$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 keyKeys 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:
$products = [
["name" => "Pen", "price" => 1.20],
["name" => "Notebook", "price" => 3.50],
];
echo $products[1]["name"]; // NotebookRead 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:
| Task | Function | Example result for ["b", "c"] |
|---|---|---|
| Add to the end | $a[] = "d" or array_push($a, "d") | ["b", "c", "d"] |
| Add to the start | array_unshift($a, "a") | ["a", "b", "c"] |
| Remove the last item | array_pop($a) | returns "c" |
| Remove the first item | array_shift($a) | returns "b" |
| Remove by key | unset($a[0]) | [1 => "c"] |
| Remove and insert in the middle | array_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:
$original = [1, 2];
$copy = $original;
$copy[] = 3;
echo count($original); // 2
echo count($copy); // 3The 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
| Function | What 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()andexplode()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.
A shopping list
<?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";Items: 4
First: milk
All: milk, bread, eggs, honey
Bread is on the listLine-by-line explanation
- Lines 3 to 4Two ways to add items to the end.
- Line 8implode() joins every item into one string with ", " between them.
- Line 9in_array() returns true, so the ternary picks the first message.
A product record
<?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";
}name: 'Water bottle'
price: 12.0
stock: 38
sale: trueLine-by-line explanation
- Lines 2 to 6Each value has a named key.
- Line 8Change a value by its key.
- Line 9Assigning to a new key adds it.
- Lines 11 to 13foreach gives both the key and the value. var_export() prints values the way PHP code would write them.
A table from an array of records
<?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);Backpack 34.99
Pen 12.00
Notebook 17.50
Total 64.49Line-by-line explanation
- Lines 2 to 6An indexed array where every item is an associative array.
- Line 10Read two keys from the current record and multiply them.
- Line 12str_pad() lines the names up; number_format() shows two decimals.
Common PHP Arrays Mistakes
Reading a key that doesn't exist
echo $user["email"]; // Warning: Undefined array keyecho $user["email"] ?? "no email";Using sort() on an associative array
$prices = ["pen" => 1.2, "lamp" => 24.5, "cup" => 8];
sort($prices); // keys are lost: [0 => 1.2, 1 => 8, 2 => 24.5]$prices = ["pen" => 1.2, "lamp" => 24.5, "cup" => 8];
asort($prices); // keeps keys: pen, cup, lampEchoing a whole array
$colours = ["red", "blue"];
echo $colours; // Array, plus a warning$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.
Complete the code so it prints Oslo.
$city = ["name" => "Oslo", "country" => "Norway"];
echo $city[""];
What does this print?
$n = [5, 10, 15];
$n[] = 20;
echo count($n);
What does this print?
$parts = explode("-", "2024-07-15");
echo $parts[1];
Which function sorts an associative array by value and keeps the keys?
What does this print?
$colours = ["red", "green"];
$colours[] = "blue";
echo count($colours) . " " . $colours[2];
PHP Arrays Quiz
5 questions to check what you learned.
What is the index of the first item in a PHP indexed array?
- 1
- 0
- "first"
- -1
Which function returns the number of items in an array?
- count()
- strlen()
- size()
- length()
What does
implode(" | ", ["a", "b", "c"])return?- ["a | b | c"]
- "abc"
- "a | b | c"
- "a b c"
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"]
How do you read the value for the key "email" in $user?
- $user.email
- $user->email
- $user(email)
- $user["email"]