ZetCode

PHP Array Functions

last modified October 22, 2026

In this article, we show how to work with arrays in PHP using various array functions. Arrays are a fundamental data structure in PHP, and the language provides a rich set of functions to manipulate them. We use both numerical and string data in the examples.

Sorting and filtering are covered in more detail in the PHP array sorting and PHP array filtering articles.

Counting elements

The count function returns the number of elements in an array.

count.php
<?php

$numbers = [1, 2, 3, 4, 5];
$fruits = [
    "apple" => "red",
    "banana" => "yellow",
    "grape" => "purple",
];
$matrix = [[1, 2], [3, 4, 5]];

echo "Number of elements in numbers array: " . count($numbers) . "\n";
echo "Number of elements in fruits array: " . count($fruits) . "\n";
echo "Top-level elements in matrix: " . count($matrix) . "\n";
echo "All elements in matrix: " . count($matrix, COUNT_RECURSIVE) . "\n";

By default, count counts only the top-level elements. With the COUNT_RECURSIVE mode, it also counts the elements of nested arrays; the two inner arrays are counted as well, which gives 2 + 5 = 7.

$ php count.php
Number of elements in numbers array: 5
Number of elements in fruits array: 3
Top-level elements in matrix: 2
All elements in matrix: 7

Joining and splitting

The implode function joins array elements into a string; explode does the opposite.

implode.php
<?php

$fruits = ['apple', 'banana', 'grape', 'orange'];

$joined = implode(', ', $fruits);
echo "Joined fruits: $joined\n";

$parts = explode(', ', $joined);
print_r($parts);

The elements of $fruits are joined into a single string separated by commas. The explode function splits the string back into an array.

$ php implode.php
Joined fruits: apple, banana, grape, orange
Array
(
    [0] => apple
    [1] => banana
    [2] => grape
    [3] => orange
)

Summing array elements

The following example computes basic statistics of a numeric array.

sum.php
<?php

$numbers = [1, 2, 3, 4, 5];

echo "Sum: " . array_sum($numbers) . "\n";
echo "Product: " . array_product($numbers) . "\n";
echo "Min: " . min($numbers) . ", Max: " . max($numbers) . "\n";
printf("Average: %.2f\n", array_sum($numbers) / count($numbers));

The array_sum and array_product functions compute the sum and product of the values. The min and max functions accept an array as well.

$ php sum.php
Sum: 15
Product: 120
Min: 1, Max: 5
Average: 3.00

Reducing an array

The array_reduce function folds an array into a single value with a callback.

reduce.php
<?php

$orders = [
    ['item' => 'Book', 'price' => 12.5, 'qty' => 2],
    ['item' => 'Pen', 'price' => 1.2, 'qty' => 10],
    ['item' => 'Bag', 'price' => 30.0, 'qty' => 1],
];

$total = array_reduce($orders, fn($carry, $order) => $carry + $order['price'] * $order['qty'], 0);

printf("Total: %.2f\n", $total);

The callback receives the accumulated value and the current element. The third argument, 0, is the initial value of the accumulator.

$ php reduce.php
Total: 67.00

Picking random elements

The array_rand function picks one or more random keys from an array.

random.php
<?php

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$randomKey = array_rand($numbers);
echo "Random element: " . $numbers[$randomKey] . "\n";

$randomKeys = array_rand($numbers, 3);
$randomElements = array_map(fn($key) => $numbers[$key], $randomKeys);

echo "Multiple random elements: " . implode(', ', $randomElements) . "\n";

With one argument, array_rand returns a single key; with a count, it returns an array of keys in their original order. The keys are then used to look up the values. The output differs on each run.

$ php random.php
Random element: 8
Multiple random elements: 4, 5, 6

Sorting arrays

The following example sorts arrays with the sort, rsort, asort, and ksort functions.

sort.php
<?php

$numbers = [3, 1, 4, 1, 5, 9];
$fruits = [
    "apple" => "red",
    "banana" => "yellow",
    "grape" => "purple",
];

sort($numbers);
echo implode(' ', $numbers), "\n";

rsort($numbers);
echo implode(' ', $numbers), "\n";

asort($fruits);
print_r($fruits);

ksort($fruits);
print_r($fruits);

The sort function sorts the $numbers array in ascending order and rsort in descending order; both reindex the array. The asort function sorts $fruits by value (purple, red, yellow) while keeping the keys, and ksort sorts it by key. All sorting functions modify the array in place.

$ php sort.php
1 1 3 4 5 9
9 5 4 3 1 1
Array
(
    [grape] => purple
    [apple] => red
    [banana] => yellow
)
Array
(
    [apple] => red
    [banana] => yellow
    [grape] => purple
)

Extracting columns

The array_column function extracts a column from a list of rows.

column.php
<?php

$records = [
    ['id' => 3, 'name' => 'John', 'age' => 25],
    ['id' => 7, 'name' => 'Jane', 'age' => 22],
    ['id' => 9, 'name' => 'Doe', 'age' => 30],
];

$names = array_column($records, 'name');
print_r($names);

$namesById = array_column($records, 'name', 'id');
print_r($namesById);

The first call returns the names in a list. The third argument tells array_column which column to use for keys, so the second call returns the names indexed by their IDs.

$ php column.php
Array
(
    [0] => John
    [1] => Jane
    [2] => Doe
)
Array
(
    [3] => John
    [7] => Jane
    [9] => Doe
)

Shuffling an array

The shuffle function randomly rearranges the elements of an array.

shuffle.php
<?php

$numbers = [1, 2, 3, 4, 5];

shuffle($numbers);

echo implode(' ', $numbers), "\n";

The array is modified in place and its keys are renumbered. The output differs on each run.

$ php shuffle.php
4 2 3 1 5

Merging arrays

Arrays can be merged with array_merge, the spread operator, or the + union operator.

merge.php
<?php

$numbers1 = [1, 2, 3];
$numbers2 = [4, 5, 6];

$defaults = ["color" => "red", "size" => "M"];
$options = ["size" => "L", "qty" => 2];

print_r(array_merge($numbers1, $numbers2));
print_r([...$numbers1, ...$numbers2]);

print_r(array_merge($defaults, $options));
print_r($defaults + $options);

For lists, array_merge and the spread operator give the same result. For string keys, they differ from the union operator: array_merge lets later values overwrite earlier ones, so size becomes L, while + keeps the value from the left array and only adds missing keys. This makes + handy for applying defaults.

$ php merge.php
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [color] => red
    [size] => L
    [qty] => 2
)
Array
(
    [color] => red
    [size] => M
    [qty] => 2
)

Filtering arrays

The array_filter function keeps the elements for which a callback returns true.

filter.php
<?php

$numbers = [1, 2, 3, 4, 5, 6];
$fruits = [
    "apple" => "red",
    "banana" => "yellow",
    "grape" => "purple",
];

$evenNumbers = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($evenNumbers);

$longFruits = array_filter($fruits, fn($key) => strlen($key) > 5, ARRAY_FILTER_USE_KEY);
print_r($longFruits);

print_r(array_filter([0, 1, '', 'a', null, false, [], '0']));

The first call keeps the even numbers. With ARRAY_FILTER_USE_KEY, the callback receives keys instead of values. Without a callback, array_filter removes all falsy values, including 0, '', '0', null, false and empty arrays. The original keys are preserved.

$ php filter.php
Array
(
    [1] => 2
    [3] => 4
    [5] => 6
)
Array
(
    [banana] => yellow
)
Array
(
    [1] => 1
    [3] => a
)

Mapping arrays

The array_map function applies a callback to each element.

map.php
<?php

$numbers = [1, 2, 3, 4, 5];
$fruits = ["apple", "banana", "grape"];

$squared = array_map(fn($n) => $n * $n, $numbers);
echo implode(' ', $squared), "\n";

$upper = array_map('strtoupper', $fruits);
echo implode(' ', $upper), "\n";

$pairs = array_map(fn($fruit, $n) => "$n:$fruit", $fruits, [10, 20, 30]);
echo implode(' ', $pairs), "\n";

The first call squares the numbers, the second applies the built-in strtoupper function. When array_map receives several arrays, it passes one element from each to the callback.

$ php map.php
1 4 9 16 25
APPLE BANANA GRAPE
10:apple 20:banana 30:grape

Searching arrays

The in_array function checks whether a value exists; array_search returns its key.

search.php
<?php

$fruits = ['apple', 'banana', 'grape', 'orange'];

var_dump(in_array('grape', $fruits));
var_dump(array_search('grape', $fruits));
var_dump(array_search('kiwi', $fruits));

$codes = ['1', '2', '3'];

var_dump(in_array(2, $codes));
var_dump(in_array(2, $codes, true));

array_search returns false when the value is not found. Both functions compare loosely by default, so the integer 2 matches the string '2'. Passing true as the third argument enables strict comparison.

Because a key can be 0, the result of array_search must be checked with === false, not with a plain if.

$ php search.php
bool(true)
int(2)
bool(false)
bool(true)
bool(false)

Finding elements with a predicate

PHP 8.4 added the array_find, array_find_key, array_any, and array_all functions.

find.php
<?php

$fruits = ['apple', 'banana', 'grape', 'orange'];

$fruit = array_find($fruits, fn($f) => str_starts_with($f, 'g'));
echo "Found fruit: $fruit\n";

$key = array_find_key($fruits, fn($f) => strlen($f) > 5);
echo "First long fruit at index: $key\n";

var_dump(array_any($fruits, fn($f) => str_contains($f, 'nan')));
var_dump(array_all($fruits, fn($f) => ctype_lower($f)));

array_find returns the first value for which the callback returns true, and array_find_key returns its key; both return null if nothing matches. array_any and array_all check whether the callback holds for at least one or for all elements.

Older code often defined its own array_find function; such definitions now fail with a Cannot redeclare function error and must be removed or renamed.

$ php find.php
Found fruit: grape
First long fruit at index: 1
bool(true)
bool(true)

Keys and values

Several functions work with keys and values separately.

keys_values.php
<?php

$capitals = ['Slovakia' => 'Bratislava', 'Hungary' => 'Budapest', 'Austria' => 'Vienna'];

print_r(array_keys($capitals));
print_r(array_values($capitals));
print_r(array_flip($capitals));

echo array_key_first($capitals), " ", array_key_last($capitals), "\n";
var_dump(array_key_exists('Poland', $capitals));

$countries = array_combine(['sk', 'hu', 'at'], array_keys($capitals));
print_r($countries);

array_keys and array_values return the keys and the values, and array_flip swaps them. array_key_first and array_key_last return the first and last key. array_key_exists checks for a key, and array_combine builds an array from a list of keys and a list of values.

$ php keys_values.php
Array
(
    [0] => Slovakia
    [1] => Hungary
    [2] => Austria
)
Array
(
    [0] => Bratislava
    [1] => Budapest
    [2] => Vienna
)
Array
(
    [Bratislava] => Slovakia
    [Budapest] => Hungary
    [Vienna] => Austria
)
Slovakia Austria
bool(false)
Array
(
    [sk] => Slovakia
    [hu] => Hungary
    [at] => Austria
)

Slicing and splicing

The array_slice function extracts a part of an array; array_splice removes and replaces a part in place.

slice.php
<?php

$letters = ['a', 'b', 'c', 'd', 'e', 'f'];

print_r(array_slice($letters, 1, 3));
print_r(array_slice($letters, -2));

$removed = array_splice($letters, 1, 2, ['X', 'Y', 'Z']);
echo implode(' ', $removed), "\n";
echo implode(' ', $letters), "\n";

print_r(array_chunk([1, 2, 3, 4, 5], 2));

A negative offset counts from the end of the array. array_splice returns the removed elements and inserts the replacement into the original array. array_chunk splits an array into pieces of a given size.

$ php slice.php
Array
(
    [0] => b
    [1] => c
    [2] => d
)
Array
(
    [0] => e
    [1] => f
)
b c
a X Y Z d e f
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 5
        )

)

Unique values and set operations

The following example removes duplicates and compares arrays.

unique.php
<?php

$a = [1, 2, 2, 3, 4, 4, 5];
$b = [4, 5, 6, 7];

echo implode(' ', array_unique($a)), "\n";
echo implode(' ', array_intersect($a, $b)), "\n";
echo implode(' ', array_diff($a, $b)), "\n";
print_r(array_count_values($a));

array_unique removes duplicate values, array_intersect returns values present in both arrays, and array_diff values present only in the first one. array_count_values counts how many times each value occurs.

$ php unique.php
1 2 3 4 5
4 4 5
1 2 2 3
Array
(
    [1] => 1
    [2] => 2
    [3] => 1
    [4] => 2
    [5] => 1
)

Creating arrays

Several functions create arrays filled with values.

fill_range.php
<?php

echo implode(' ', range(1, 10, 3)), "\n";
echo implode(' ', range('a', 'e')), "\n";
echo implode(' ', array_fill(0, 4, '-')), "\n";
print_r(array_fill_keys(['red', 'green'], 0));
echo implode(' ', array_pad([1, 2], 5, 0)), "\n";

range creates a sequence of numbers or letters with an optional step. array_fill and array_fill_keys fill an array with a single value, and array_pad extends an array to a given length.

$ php fill_range.php
1 4 7 10
a b c d e
- - - -
Array
(
    [red] => 0
    [green] => 0
)
1 2 0 0 0

Checking for lists

The array_is_list function, added in PHP 8.1, checks whether the keys of an array are 0, 1, 2, ... in order.

is_list.php
<?php

var_dump(array_is_list([1, 2, 3]));
var_dump(array_is_list([1 => 'a', 2 => 'b']));
var_dump(array_is_list(['x' => 1]));

$filtered = array_filter([1, 2, 3, 4], fn($n) => $n > 2);
var_dump(array_is_list($filtered));
var_dump(array_is_list(array_values($filtered)));

Arrays with other keys are not lists. Because array_filter preserves keys, its result is usually not a list; array_values turns it into one. This matters, for instance, for json_encode, which encodes lists as JSON arrays and other arrays as objects.

$ php is_list.php
bool(true)
bool(false)
bool(false)
bool(false)
bool(true)

Source

PHP Array Functions - Documentation

In this article, we have shown how to work with arrays in PHP using various array functions for counting, searching, transforming, and combining arrays.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all PHP tutorials.