PHP Array

Beginner
10 min read
Updated: Nov 2026
3 examples
Lists, maps, sorting & callbacks

Definition and Usage

A PHP array holds many values under one variable name. Under the hood it is an ordered map: every value sits under a key, and the keys are integers or strings. The same type works as a plain list, a lookup table, a stack, a queue, or a set, which is why arrays show up in almost every PHP script.

You build one with the short syntax [] or the older array() construct. You read its size with count(), test for a value with in_array(), and add or remove items at either end with array_push(), array_pop(), array_shift() and array_unshift().

To change many items at once, use a callback: array_map() transforms, array_filter() selects, and array_reduce() folds everything into one value. Combine arrays with array_merge(), array_diff() and array_intersect(), and order them with sort() and its relatives.

This page explains the ideas. The Array Functions index lists all 88 function guides.

Pick the right tool.

Use count() and in_array() to inspect, the four stack functions to add or remove at the ends, array_map(), array_filter() and array_reduce() to transform, and the sort family to order. Almost every array function either returns a new array or changes the one you pass by reference, so check which one before you rely on the result.

Arrays are copied, not shared.

Assigning $b = $a gives $b its own copy of the values. Changing $b later does not change $a. Only functions that take the array by reference, such as sort() and array_push(), change the variable you pass in.

Some old functions are gone.

each() was removed in PHP 8.0, so avoid it in new code and use foreach instead. The index still documents it for old code you may meet. list() is a language construct, not a real function, and the short form [$a, $b] = $array does the same job.

PHP Syntax

The usual pattern: create an array, inspect it, change it, then loop or transform it:

PHP
// create: a list and an associative array
$fruits = ['apple', 'banana', 'cherry'];
$stock  = ['apple' => 5, 'banana' => 0, 'cherry' => 12];

// inspect
echo count($fruits);                          // 3
var_dump(in_array('banana', $fruits, true));  // bool(true)
echo $stock['cherry'];                        // 12

// stack and queue
$fruits[] = 'date';                           // append (same as array_push)
array_unshift($fruits, 'avocado');            // add to the front
$last  = array_pop($fruits);                  // remove from the end
$first = array_shift($fruits);                // remove from the front

// transform with callbacks
$lengths = array_map('strlen', $fruits);               // [5, 6, 6]
$stocked = array_filter($stock, fn($n) => $n > 0);    // apple, cherry
$total   = array_reduce($stock, fn($c, $n) => $c + $n, 0);   // 17

// combine and compare
$all    = array_merge(['a', 'b'], ['c']);              // a, b, c
$only   = array_diff(['a', 'b', 'c'], ['b']);          // a, c
$shared = array_intersect(['a', 'b'], ['b', 'c']);     // b

// order
sort($fruits);                                // by value, new keys
ksort($stock);                                // by key, keeps values

// keys and values
$names  = array_keys($stock);                 // apple, banana, cherry
$counts = array_values($stock);               // 5, 0, 12

Core Ideas

What to remember when you work with PHP arrays:

IdeaFunctionRemember
Createarray() / range() / compact()[] and array() are the same; range(1, 5) builds [1, 2, 3, 4, 5]; compact() builds an array from variable names
Size and searchcount() / in_array() / array_search()count() has the alias sizeof(); pass true to in_array() for a strict match; array_search() returns the key or false
Key checksarray_key_exists() / array_keys() / array_values()array_key_exists() finds keys even when the value is null; array_values() renumbers to 0, 1, 2
Stack and queuearray_push() / array_pop() / array_shift() / array_unshift()Push and pop work at the end; shift and unshift work at the front. All four change the array you pass in
Callbacksarray_map() / array_filter() / array_reduce()Map changes each value, filter keeps some (and their keys), reduce returns a single value. None of them changes the original
Combinearray_merge() / array_diff() / array_intersect()Merge joins arrays, diff keeps what is only in the first, intersect keeps what is in all. Variants such as _key, _assoc and u compare keys or use your own function
Sortsort() / asort() / ksort() / usort()A leading r reverses (rsort); a keeps keys with values; k sorts by key; u uses your comparison function
Slice and reshapearray_slice() / array_splice() / array_reverse() / array_unique()array_slice() returns a piece and leaves the original alone; array_splice() removes or replaces a piece in place

Passing by reference

The sort functions, the four stack functions, shuffle() and array_splice() change the array in place and return a simple value. Do not write $fruits = sort($fruits);, because sort() returns true, not the sorted array. By contrast, array_map(), array_filter(), array_merge() and array_slice() return a new array that you must assign to a variable.

Lists vs Associative Arrays

PHP has one array type, but you use it in two common shapes. A list has the keys 0, 1, 2 in order. An associative array uses names as keys. Knowing which shape you have tells you which functions are safe to use.

List (indexed)Associative
Example['apple', 'banana']['apple' => 5, 'banana' => 0]
KeysIntegers 0, 1, 2 in orderStrings (or any integers) you choose
Best forOrdered items you loop overRecords and lookups by name
Read one item$list[1]$map['banana']
Sort by valuesort() (renumbers the keys)asort() (keeps the keys)
Check the shapearray_is_list() returns true only when the keys are 0, 1, 2 in order (PHP 8.1+)

A list can turn into a non-list without warning. After unset($list[1]) or after array_filter() the keys have gaps, so array_is_list() returns false. Call array_values() to renumber the keys when you need a list again.

PHP 8.x Array Helpers

Newer PHP versions add small helpers that replace common foreach loops. They are short, so here is the whole set at a glance:

PHP
// PHP 8.1: is the array a list?
var_dump(array_is_list([10, 20, 30]));            // bool(true)
var_dump(array_is_list([1 => 'a', 2 => 'b']));    // bool(false)

// PHP 8.4: search with a callback (value, key)
$numbers = [3, 8, 12, 5];
echo array_find($numbers, fn($n) => $n > 6);               // 8
echo array_find_key($numbers, fn($n) => $n > 6);           // 1
var_dump(array_any($numbers, fn($n) => $n > 10));        // bool(true)
var_dump(array_all($numbers, fn($n) => $n > 2));         // bool(true)
FunctionPHPReturns
array_is_list()8.1true when the keys are 0, 1, 2 in order
array_find()8.4The first value the callback accepts, or null
array_find_key()8.4The key of the first value the callback accepts, or null
array_any()8.4true if at least one element passes the callback
array_all()8.4true if every element passes the callback (an empty array gives true)
array_first() / array_last()8.5The first or last value, or null for an empty array
Check your PHP version.

On PHP older than 8.4, calling array_find() gives Call to undefined function. Run echo PHP_VERSION; to see what your server uses. The examples below avoid the 8.4 functions, so they run on any PHP 8.1 or newer.

PHP Examples

Three short scripts that show how arrays work. Each one uses fixed fruits and numbers, so the output is the same every time you run it.

Example 1 — Create, count, search, push and pop

Start with a list of fruits and a stock table, then search them and add and remove items at both ends.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry'];
$stock  = ['apple' => 5, 'banana' => 0, 'cherry' => 12];

echo "Fruits: ", count($fruits), PHP_EOL;
echo "Has banana: ", in_array('banana', $fruits, true) ? 'yes' : 'no', PHP_EOL;
echo "Has grape: ", in_array('grape', $fruits, true) ? 'yes' : 'no', PHP_EOL;
echo "Cherry stock: ", $stock['cherry'], PHP_EOL;

array_push($fruits, 'date');
array_unshift($fruits, 'avocado');
echo "After adding: ", implode(', ', $fruits), PHP_EOL;

$last  = array_pop($fruits);
$first = array_shift($fruits);
echo "Removed: $first and $last", PHP_EOL;
echo "Now: ", implode(', ', $fruits), PHP_EOL;
?>

How It Works

  1. count($fruits) returns the number of elements, 3. in_array(..., true) does a strict search and returns a boolean, so 'banana' is found and 'grape' is not.
  2. $stock['cherry'] reads a value by its key. This is the associative shape: the key is a name, not a position.
  3. array_push() adds 'date' at the end and array_unshift() adds 'avocado' at the front, so the list grows to five items.
  4. array_pop() removes and returns the last item (date) and array_shift() removes and returns the first (avocado). The array is back to its three original fruits.

Example 2 — array_map(), array_filter() and array_reduce()

Square a list of numbers, keep the even ones, and add them all up. The original array never changes.

PHP
<?php
$numbers = [1, 2, 3, 4, 5, 6];

$squares = array_map(fn($n) => $n * $n, $numbers);
echo "Squares: ", implode(', ', $squares), PHP_EOL;

$even = array_filter($numbers, fn($n) => $n % 2 === 0);
echo "Even: ", implode(', ', $even), PHP_EOL;
echo "Even keys: ", implode(', ', array_keys($even)), PHP_EOL;

$reindexed = array_values($even);
echo "Reindexed keys: ", implode(', ', array_keys($reindexed)), PHP_EOL;

$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
echo "Sum: ", $sum, PHP_EOL;
echo "Original: ", implode(', ', $numbers), PHP_EOL;
?>

How It Works

  1. array_map() runs the arrow function on every element and returns a new array of the results. Squaring 1 to 6 gives 1, 4, 9, 16, 25, 36.
  2. array_filter() keeps the elements for which the callback returns true. The even numbers are 2, 4 and 6, and they keep their original keys 1, 3 and 5.
  3. array_values() renumbers the keys to 0, 1, 2. Use it when you need a clean list after filtering.
  4. array_reduce() carries a running total through the array. It starts at 0 and adds each number, ending at 21. The last line shows that $numbers was not changed by any of the three calls.

Example 3 — Merge, diff, intersect and sort

Compare two fruit lists, then sort a list of numbers and a stock table by value and by key.

PHP
<?php
$a = ['apple', 'banana', 'cherry'];
$b = ['banana', 'cherry', 'date'];

echo "Merge: ", implode(', ', array_merge($a, $b)), PHP_EOL;
echo "Unique: ", implode(', ', array_unique(array_merge($a, $b))), PHP_EOL;
echo "Diff: ", implode(', ', array_diff($a, $b)), PHP_EOL;
echo "Intersect: ", implode(', ', array_intersect($a, $b)), PHP_EOL;

$numbers = [30, 5, 12, 8];
sort($numbers);
echo "sort: ", implode(', ', $numbers), PHP_EOL;
rsort($numbers);
echo "rsort: ", implode(', ', $numbers), PHP_EOL;

$stock = ['cherry' => 12, 'apple' => 5, 'banana' => 0];
ksort($stock);
echo "ksort: ", implode(', ', array_keys($stock)), PHP_EOL;
asort($stock);
echo "asort keys: ", implode(', ', array_keys($stock)), PHP_EOL;
echo "asort values: ", implode(', ', array_values($stock)), PHP_EOL;

echo "numbers is a list: ", array_is_list($numbers) ? 'yes' : 'no', PHP_EOL;
echo "stock is a list: ", array_is_list($stock) ? 'yes' : 'no', PHP_EOL;
?>

How It Works

  1. array_merge() joins the two lists and keeps duplicates. array_unique() drops the repeats, leaving four fruits.
  2. array_diff($a, $b) keeps the values that are in $a but not in $b, which is only apple. array_intersect() keeps the values found in both, banana and cherry.
  3. sort() orders the numbers from low to high and rsort() from high to low. Both change $numbers in place and renumber the keys.
  4. ksort() sorts the stock table by key, and asort() then sorts it by value while each value keeps its key. That is why the keys come out as banana, apple, cherry for the values 0, 5, 12.
  5. array_is_list() (PHP 8.1) says yes for the numbers, whose keys are 0 to 3, and no for the stock table, whose keys are names.

Next: PHP Array Functions Index

After you know how arrays, callbacks, and sorting fit together, open the functions index for all 88 guides.

Start withWhy
count()Get the number of elements in an array
in_array()Check whether a value exists in an array
array_map()Apply a callback to every element
array_filter()Keep only the elements that pass a test
array_merge()Join two or more arrays into one
sort()Sort a list by value
array_find()Find the first matching value with a callback (PHP 8.4)

Full list: PHP Array Functions index (/php/array/function).

Frequently Asked Questions

A PHP array is an ordered map that holds many values under one variable name. Each value is stored under a key, which is either an integer or a string. You can create one with the short syntax [] or with the array() construct, and it can hold values of any type, including other arrays.
An indexed array (a list) uses the keys 0, 1, 2 and so on in order, for example ['apple', 'banana']. An associative array uses names you choose as keys, for example ['apple' => 5, 'banana' => 0]. Both are the same type in PHP; the only difference is how the keys look. array_is_list() returns true when the keys are 0, 1, 2 in order.
Use in_array($needle, $array, true) to look for a value, and array_key_exists($key, $array) to look for a key. Pass true as the third argument of in_array() for a strict comparison, so that the string '1' does not match the integer 1. array_key_exists() also finds keys whose value is null, which isset() does not.
array_filter() removes elements but does not renumber the rest, so the original keys stay. Filtering [1, 2, 3, 4, 5, 6] for even numbers leaves the keys 1, 3 and 5. Wrap the result in array_values() when you need a clean list that starts at 0.
Use array_map() to turn every element into a new value, array_filter() to keep only the elements that pass a test, and array_reduce() to boil the whole array down to one value such as a sum. They take a callback and return a result without changing the original array.
They are PHP 8.4 helpers that take a callback. array_find() returns the first value that passes the test (or null), array_find_key() returns its key, array_any() returns true if at least one element passes, and array_all() returns true only if every element passes. Before PHP 8.4 you wrote a foreach loop for the same job.
Use sort() or rsort() for a plain list when you do not need the old keys. Use asort() or arsort() to sort by value and keep the keys, and ksort() or krsort() to sort by key. Use usort(), uasort() or uksort() when you need your own comparison rule.

Browse every Array function

Open the functions index for categorized guides with examples and FAQs.

Array Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful