W3docs

Understanding PHP Array Functions: A Comprehensive Guide

Arrays in PHP are a fundamental data structure for any developer. They allow you to store and manipulate a collection of values in a single variable. In this

An array in PHP is a single variable that holds a collection of values. Instead of declaring $user1, $user2, $user3, you store them all in one array and access them by an index (a number) or a key (a name). Arrays are one of the most-used building blocks in PHP — request data ($_POST, $_GET), database rows, and configuration are all delivered to you as arrays.

This chapter explains the three kinds of PHP array, how to create and read them, how to loop over them, and the built-in functions you'll reach for most often.

Three kinds of array

PHP has one array type internally, but you'll see it used in three distinct ways:

KindKeysTypical use
IndexedAutomatic integers 0, 1, 2…An ordered list of items
AssociativeStrings you chooseA record with named fields
MultidimensionalArrays nested inside arraysTables, grouped data

Creating arrays

The modern short syntax uses square brackets []; the older array() form is equivalent and still works.

<?php

// Indexed array — keys 0, 1, 2 are assigned automatically
$fruits = ["apple", "banana", "cherry"];

// Associative array — you choose the keys
$user = [
    "name"  => "Ada",
    "email" => "[email protected]",
    "admin" => true,
];

echo $fruits[0];      // apple
echo $user["name"];   // Ada

Add to an array with the empty-bracket syntax, which appends to the end:

<?php

$fruits = ["apple", "banana"];
$fruits[] = "cherry";      // index 2
$fruits[] = "date";        // index 3

print_r($fruits);
// Array ( [0] => apple [1] => banana [2] => cherry [3] => date )

Use indexed arrays, associative arrays, and multidimensional arrays for deeper coverage of each kind.

Looping over an array

The foreach loop is the idiomatic way to walk an array, because it gives you the key and value directly without manual index bookkeeping:

<?php

$user = ["name" => "Ada", "email" => "[email protected]"];

foreach ($user as $key => $value) {
    echo "$key: $value\n";
}
// name: Ada
// email: [email protected]

See the foreach loop chapter for the full syntax, including looping by reference.

How array functions work

PHP ships hundreds of array functions — predefined helpers that perform a specific operation so you don't have to write the loop yourself. A key thing to understand: most of them return a new array and leave the original untouched (array_map, array_filter, array_merge…), while a smaller group modify the array in place and return something else (sort returns true, array_push returns the new length). Knowing which is which avoids a common class of bugs.

You call a function by passing the array as an argument. For example, array_sum adds up every value:

php— editable, runs on the server

Functions you'll use most

FunctionWhat it doesMutates?
count()Number of elementsno
in_array()Is a value present?no
array_keys()All the keys as an arrayno
array_values()All the values, re-indexed from 0no
array_merge()Join two or more arraysno
array_slice()Extract a portionno
array_unique()Remove duplicate valuesno
array_push()Append one or more valuesyes
sort()Sort values ascendingyes

Here are the three workhorse callback functions — map, filter, and reduce — which cover most data-shaping tasks.

array_map — transform every element

array_map runs a callback on each value and returns a new array of the results, same length as the original:

<?php

$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n * $n, $numbers);

print_r($squared);
// Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )

array_filter — keep only what matches

array_filter keeps the elements for which the callback returns true. Note that it preserves the original keys, so you often follow it with array_values() to re-index:

<?php

$numbers = [1, 2, 3, 4, 5, 6];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);

print_r($even);
// Array ( [1] => 2 [3] => 4 [5] => 6 )   ← keys kept

print_r(array_values($even));
// Array ( [0] => 2 [1] => 4 [2] => 6 )   ← re-indexed

array_reduce — collapse to a single value

array_reduce applies a callback that carries an accumulator ($carry) across the whole array, reducing it to one result — a sum, a string, a max, anything:

php— editable, runs on the server

See array_map, array_filter, and array_reduce for full details, and PHP callback functions for how callbacks work.

Common gotchas

  • array_filter preserves keys. As shown above, the result is no longer 0, 1, 2…. Wrap it in array_values() when you need a clean list.
  • array_merge re-numbers integer keys but overwrites string keys. array_merge(["a" => 1], ["a" => 2]) gives ["a" => 2], while two indexed arrays are concatenated, not overwritten.
  • Mutating vs. returning. sort($arr) changes $arr and returns true — writing $arr = sort($arr) is a classic bug that sets $arr to true.
  • Accessing a missing key emits a warning and returns null. Guard with isset() or array_key_exists() first.

Conclusion

PHP arrays come in three flavors — indexed, associative, and multidimensional — and a large library of functions exists to query, transform, and combine them. Reach for foreach to iterate, array_map / array_filter / array_reduce to reshape data, and keep the mutate-vs-return distinction in mind to avoid surprises. From here, explore sorting arrays and PHP functions to round out your toolkit.

Practice

Practice
What statements are true regarding Arrays in PHP?
What statements are true regarding Arrays in PHP?
Was this page helpful?