W3docs

Understanding PHP Arrays

PHP arrays are data structures used to store collections of variables. They are a key component of PHP programming and essential for managing large amounts of

A PHP array is an ordered map: a single variable that holds many values, each reachable by a key. Instead of declaring $fruit1, $fruit2, $fruit3, you keep one $fruits array and address its items by position or by name. Arrays are the workhorse data structure in PHP — query results, form input ($_POST), configuration, and JSON all arrive as arrays.

This chapter covers the three kinds of arrays, how to create and read them, how to add, remove, and merge elements, how to loop over them, and the common gotchas that trip people up. Each runnable example prints its result so you can see exactly what PHP produces.

Types of PHP Arrays

PHP has three array forms, and under the hood they are all the same type — an ordered map of key/value pairs:

  • Indexed arrays use automatic integer keys starting at 0.
  • Associative arrays use string keys you choose yourself.
  • Multidimensional arrays store other arrays as values, letting you build tables and nested structures.
// Indexed: keys 0, 1, 2 are assigned automatically
$fruits = ["apple", "banana", "cherry"];

// Associative: you pick the keys
$colors = ["apple" => "red", "banana" => "yellow", "cherry" => "dark red"];

// Multidimensional: values are themselves arrays
$basket = [
    ["name" => "apple",  "qty" => 4],
    ["name" => "banana", "qty" => 6],
];

Each form has its own dedicated chapter: indexed arrays, associative arrays, and multidimensional arrays.

Creating PHP Arrays

There are two equivalent syntaxes. The short [] syntax (PHP 5.4+) is preferred in modern code; the older array() function does exactly the same thing.

// Short array syntax — recommended
$fruits = ["apple", "banana", "cherry"];

// Long syntax with the array() language construct
$fruits = array("apple", "banana", "cherry");

You can also build an array incrementally. Assigning to $arr[] appends with the next integer key, and assigning to a named key creates or overwrites that entry:

$fruits = [];
$fruits[] = "apple";     // key 0
$fruits[] = "banana";    // key 1
$fruits["best"] = "fig"; // string key "best"

Accessing Elements of an Array

Read a value with [], passing an integer index for indexed arrays or a string key for associative ones.

<?php
$fruits = ["apple", "banana", "cherry"];
$colors = ["apple" => "red", "banana" => "yellow"];

echo $fruits[0];        // apple
echo "\n";
echo $colors["apple"];  // red
?>

Reading a key that does not exist emits a warning and yields null. Check first with isset() (true only when the key exists and is not null) or array_key_exists() (true even when the stored value is null), or supply a fallback with the null-coalescing operator:

<?php
$colors = ["apple" => "red"];

$banana = $colors["banana"] ?? "unknown"; // no warning, returns "unknown"
echo $banana;
?>

Adding and Removing Elements

PHP ships dedicated functions for changing an array from either end:

  • array_push($arr, $value) — add to the end (or just use $arr[] = $value).
  • array_pop($arr) — remove and return the last element.
  • array_unshift($arr, $value) — add to the beginning.
  • array_shift($arr) — remove and return the first element, re-indexing the rest.
  • unset($arr[$key]) — delete a specific element (this leaves a gap in integer keys).
<?php
$fruits = ["apple", "banana", "cherry"];

array_push($fruits, "mango"); // ["apple","banana","cherry","mango"]
$last = array_pop($fruits);   // $last = "mango"
unset($fruits[1]);            // removes "banana", keys 0 and 2 remain

print_r($fruits);
?>

Output:

Array
(
    [0] => apple
    [2] => cherry
)

Note the missing [1]unset() does not renumber. To compact the keys back to 0, 1, 2…, run array_values($fruits). For more detail see array_push and array_pop.

Looping Over Arrays

foreach is the idiomatic way to walk an array; it works for both indexed and associative arrays and gives you the key as well as the value.

<?php
$colors = ["apple" => "red", "banana" => "yellow", "cherry" => "dark red"];

foreach ($colors as $fruit => $color) {
    echo "$fruit is $color\n";
}
?>

Output:

apple is red
banana is yellow
cherry is dark red

See the foreach loop chapter, and the broader PHP loops overview, for more patterns.

Merging Arrays

array_merge() combines two or more arrays into a new one. Be aware of how it treats keys: integer keys are renumbered, but string keys collide — a later array's value overwrites an earlier one with the same string key.

php— editable, runs on the server

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
    [3] => mango
)

If you only need to append numbered arrays, the spread operator is a concise alternative: $all = [...$fruits1, ...$fruits2];. For string-keyed merges where the first value should win, use the + union operator instead. More in the array_merge chapter.

Useful Array Helpers

PHP's standard library has dozens of array functions. A handful you will reach for constantly:

FunctionWhat it does
count($arr)Number of elements
in_array($v, $arr)Whether a value exists (details)
array_keys($arr)All the keys as a new array (details)
array_values($arr)All the values, re-indexed from 0
sort($arr)Sort values in place (sorting arrays)
<?php
$fruits = ["apple", "banana", "cherry"];

echo count($fruits);                              // 3
echo "\n";
echo in_array("banana", $fruits) ? "yes" : "no";  // yes
?>

Common Gotchas

  • Keys are unique. Assigning to an existing key overwrites it rather than adding a second entry.
  • "1" and 1 collide. Numeric string keys are cast to integers, so $a["1"] and $a[1] are the same slot.
  • Arrays are copied by value. Passing an array to a function gives that function a copy; the original is unchanged unless you pass it by reference (&$arr).
  • unset() leaves holes. Use array_values() afterward if you need a clean, contiguous index.

Conclusion

PHP arrays are the foundation for storing and organizing data — from a simple list of values to nested records. Master the three forms, the create/read/add/remove operations, foreach, and a few helper functions, and you can handle the vast majority of real-world data tasks in PHP. From here, dig into indexed arrays, associative arrays, and sorting arrays.

Practice

Practice
What are the different types of arrays in PHP?
What are the different types of arrays in PHP?
Was this page helpful?