PHP Arrays
An array is a single PHP variable that can hold many values at once, each reachable through a key.
What is an array in PHP?
When you need to store a list of related values, creating a separate variable for each one quickly becomes unmanageable. An array solves this by letting a single variable hold an ordered collection of values. Every value inside the array is paired with a key, and you use that key to read or change the value later. PHP is unusual in that its arrays are extremely flexible: the same array type is used for numbered lists, key-value maps, and nested structures.
The most common way to build an array is with the short square-bracket syntax introduced in PHP 5.4. The older array() function does exactly the same thing and still works, so you will see both styles in real projects.
Creating your first array
<?php
$fruits = ["apple", "banana", "cherry"];
// The older, equivalent style
$colors = array("red", "green", "blue");
echo $fruits[0]; // apple
echo $colors[2]; // blue
?>The three kinds of arrays
- Indexed arrays use automatic numeric keys starting at 0, which is ideal for ordered lists.
- Associative arrays use named string keys that you choose, which is ideal for records like a user profile.
- Multidimensional arrays store other arrays as their values, letting you model tables, grids, and nested data.
Under the hood these are all the same data type, so a single array can even mix numeric and string keys. To inspect what an array actually contains, print_r() and var_dump() are your best friends during development. count() tells you how many top-level elements an array holds.
Inspecting and counting elements
<?php
$scores = [90, 85, 72];
echo count($scores); // 3
print_r($scores);
/*
Array
(
[0] => 90
[1] => 85
[2] => 72
)
*/
?>Modifying an array
Arrays are not fixed in size. You can append a value by assigning to an empty bracket pair, which lets PHP pick the next numeric key for you, and you can overwrite an existing value by targeting its key directly.
Adding and changing values
<?php
$tasks = ["write code"];
$tasks[] = "review PR"; // appended at key 1
$tasks[] = "deploy"; // appended at key 2
$tasks[0] = "write tests"; // overwrites the first value
print_r($tasks);
// [write tests, review PR, deploy]
?>Exercise: PHP Arrays
What distinguishes an associative array from an indexed array?