Himanshu SharmaSoftware engineer
Let’s talk

PHP · Lesson 25 of 54

Common array functions

Use PHP's most useful array functions to count, search, slice, merge, split, combine, deduplicate and convert arrays to and from strings.

14 minArraysUpdated 22 October 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonPick the right built-in function to search, slice, merge, deduplicate or join an array instead of writing a loop.

Let PHP do the looping

PHP has around eighty functions for working with arrays. You do not need all of them, but knowing the common ones saves you writing the same small loops again and again, and makes code easier to read: in_array($code, $codes, true) says what it does more clearly than a loop with a flag. This lesson collects the everyday ones. Sorting and the callback functions have their own lessons.

Asking questions

php
<?php
$stock = ["Keyboard" => 60, "Headphones" => 25, "Desk Mat" => 40, "Puzzle" => 0];

echo count($stock) . "\n";
var_dump(array_key_exists("Puzzle", $stock));
var_dump(in_array(25, $stock, true));
var_dump(array_search(40, $stock, true));
print_r(array_keys($stock));
print_r(array_values($stock));
result
4
bool(true)
bool(true)
string(8) "Desk Mat"
Array
(
    [0] => Keyboard
    [1] => Headphones
    [2] => Desk Mat
    [3] => Puzzle
)
Array
(
    [0] => 60
    [1] => 25
    [2] => 40
    [3] => 0
)

array_search() returns the key of the first matching value, or false if there is none. Because a key can be 0, always compare its result with === false. array_keys() also takes a value to search for, which returns every key that has it: array_keys($stock, 0) lists the sold-out products.

Totals, smallest and largest

php
<?php
$prices = [89.5, 18.75, 24.99, 199.99, 12];

echo array_sum($prices) . "\n";
echo array_product([2, 3, 4]) . "\n";
echo max($prices) . " / " . min($prices) . "\n";
echo round(array_sum($prices) / count($prices), 2) . "\n";
result
345.23
24
199.99 / 12
69.05

There is no array_average(); divide the sum by the count, and check that the array is not empty first.

Taking part of an array

array_slice() returns a piece of an array without changing the original. It takes an offset (negative counts from the end) and an optional length:

php
<?php
$posts = ["Post 1", "Post 2", "Post 3", "Post 4", "Post 5", "Post 6", "Post 7"];

print_r(array_slice($posts, 0, 3));        // first page of 3
print_r(array_slice($posts, 3, 3));        // second page
print_r(array_slice($posts, -2));          // last two
echo count($posts) . " posts, unchanged\n";
result
Array
(
    [0] => Post 1
    [1] => Post 2
    [2] => Post 3
)
Array
(
    [0] => Post 4
    [1] => Post 5
    [2] => Post 6
)
Array
(
    [0] => Post 6
    [1] => Post 7
)
7 posts, unchanged

That is simple pagination: page $n of size $size is array_slice($items, ($n - 1) * $size, $size). array_splice() is the destructive cousin: it removes or replaces elements in place.

array_chunk() splits an array into pieces of a given size, handy for laying products out in rows of three.

Merging and combining

php
<?php
print_r(array_merge(["a", "b"], ["c"]));
print_r(array_merge(["currency" => "INR", "perPage" => 20], ["perPage" => 50]));
print_r(array_combine(["name", "price"], ["Yoga Mat", 24.99]));
print_r(array_fill_keys(["red", "blue"], 0));
result
Array
(
    [0] => a
    [1] => b
    [2] => c
)
Array
(
    [currency] => INR
    [perPage] => 50
)
Array
(
    [name] => Yoga Mat
    [price] => 24.99
)
Array
(
    [red] => 0
    [blue] => 0
)

array_merge() renumbers numeric keys and lets later arrays win for string keys. That is the opposite of the + operator from Indexed and associative arrays, where the first array wins. array_combine() pairs a list of keys with a list of values, which is useful for turning a CSV header row and a data row into an associative array.

Removing duplicates and finding differences

php
<?php
$tags = ["php", "mysql", "php", "html", "mysql"];
print_r(array_values(array_unique($tags)));

$wanted = ["php", "css", "laravel"];
$known = ["php", "html", "css"];
print_r(array_values(array_diff($wanted, $known)));
print_r(array_values(array_intersect($wanted, $known)));
result
Array
(
    [0] => php
    [1] => mysql
    [2] => html
)
Array
(
    [0] => laravel
)
Array
(
    [0] => php
    [1] => css
)

array_unique() keeps the first occurrence of each value but keeps the original keys, so wrapping it in array_values() gives a clean list. array_diff() returns the values of the first array that are missing from the others; array_intersect() returns the values they share. Versions ending in _key compare keys instead.

Flipping, reversing and counting values

php
<?php
$votes = ["yes", "no", "yes", "yes", "abstain"];
print_r(array_count_values($votes));
print_r(array_reverse([1, 2, 3]));
print_r(array_flip(["a" => 1, "b" => 2]));
result
Array
(
    [yes] => 3
    [no] => 1
    [abstain] => 1
)
Array
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Array
(
    [1] => a
    [2] => b
)

array_count_values() builds a frequency table in one call. array_flip() swaps keys and values, which turns a list into a fast lookup: isset($allowed[$value]) is quicker than in_array() on a large list.

Arrays and strings

implode() joins elements into a string with a separator, and explode() splits a string into an array:

php
<?php
$tags = ["php", "mysql", "html"];
echo implode(", ", $tags) . "\n";

$line = "Asha,Verma,Delhi,India";
$parts = explode(",", $line);
print_r($parts);

[$first, $rest] = explode(" ", "Kavya Nair Menon", 2);
echo "$first | $rest\n";
result
php, mysql, html
Array
(
    [0] => Asha
    [1] => Verma
    [2] => Delhi
    [3] => India
)
Kavya | Nair Menon

The optional third argument of explode() limits the number of pieces, so the last piece keeps the rest of the string. For real CSV data, with quotes and commas inside fields, use str_getcsv() or fgetcsv() instead of explode(); the files lesson shows how.

range() creates a list of numbers or letters: range(1, 5) is [1, 2, 3, 4, 5] and range('a', 'e') gives five letters.

Common mistakes

  • Comparing array_search() with == false, which fails when the match is at key 0.
  • Forgetting that array_unique() and array_filter() keep keys. Add array_values() when you need a list.
  • Mixing up array_merge() and + for settings arrays.
  • Using explode() for CSV files whose fields can contain commas.

Exercise

You have a string of tags typed by a user: "php, MySQL, html, php , css, mysql". Produce a clean, comma-separated list of unique lowercase tags in their original order: php, mysql, html, css.

Show one possible answer
php
<?php
$input = "php, MySQL, html, php , css, mysql";

$tags = explode(",", $input);
$tags = array_map("trim", $tags);
$tags = array_map("strtolower", $tags);
$tags = array_values(array_unique($tags));

echo implode(", ", $tags) . "\n";
result
php, mysql, html, css

array_map() applies a function to every element; it is explained in array_map, array_filter and array_reduce.

Key points

  • count, in_array, array_search, array_key_exists, array_keys and array_values answer questions about an array.
  • array_slice copies part of an array; array_splice removes or replaces part of it in place.
  • array_merge renumbers numeric keys and lets later string keys win; + keeps the first.
  • implode joins an array into a string; explode splits a string into an array.

Check yourself

1. What does implode(', ', ['a', 'b', 'c']) return?
2. What does array_slice([10, 20, 30, 40], 1, 2) return?
3. What does array_unique([3, 1, 3, 2, 1]) keep?
4. What does array_merge(['a' => 1], ['a' => 2]) return?