Array Functions

Yo Yogesh.M Updated 01 Nov 2026
7 min read ·Lesson 211 of 219

PHP includes more than 80 built-in array functions. Knowing which ones exist — and which one fits a task — lets you replace many hand-written loops with a single, well-tested function call. This lesson is a categorized reference with examples for functions not covered in detail in earlier lessons, plus a few rules that apply to all of them.


General Rules

  1. Most functions return a new array and leave the input unchanged: array_map(), array_filter(), array_merge(), array_slice(), array_reverse(), and others.
  2. Some functions modify the array in place (they take it by reference) and return something else: all sort functions, array_push(), array_pop(), array_shift(), array_unshift(), array_splice(), shuffle(), array_walk().
  3. Key handling differs: some functions preserve keys (array_filter(), asort(), array_slice() for string keys), others re-index (sort(), array_values(), array_merge() for integer keys). Check the manual when keys matter.
  4. Comparison mode: search functions compare loosely unless you pass true for strict mode (in_array(), array_search(), array_keys()).

Reference by Category

Inspecting

FunctionPurpose
count($array)Number of elements
array_is_list($array)true if keys are exactly 0, 1, 2, … (PHP 8.1+)
array_key_first() / array_key_last()First / last key (PHP 7.3+)
array_first() / array_last()First / last value (PHP 8.5+)
array_key_exists($key, $array)Does the key exist?

Keys and Values

FunctionPurpose
array_keys($array)All keys (or keys with a given value)
array_values($array)All values, re-indexed
array_flip($array)Swap keys and values
array_column($records, $column, $indexKey)One column from a list of records
array_combine($keys, $values)Build from two arrays
array_fill_keys($keys, $value)Given keys, same value

Adding, Removing, Extracting

FunctionPurpose
array_push(), array_pop()Add / remove at the end
array_unshift(), array_shift()Add / remove at the start
array_splice()Remove or insert at a position
array_slice($array, $offset, $length)Extract a portion (non-destructive)
array_chunk($array, $size)Split into chunks
array_pad($array, $size, $value)Extend to a size
array_unique($array)Remove duplicate values

Combining and Comparing

FunctionPurpose
array_merge(), array_replace(), +Combine arrays (see Merge Arrays)
array_merge_recursive(), array_replace_recursive()Combine nested arrays
array_diff($a, $b)Values in $a not in $b
array_diff_key($a, $b)Keys in $a not in $b
array_diff_assoc($a, $b)Key–value pairs in $a not in $b
array_intersect($a, $b)Values present in both
array_intersect_key($a, $b)Keys present in both

Transforming

FunctionPurpose
array_map()Transform each element
array_filter()Keep matching elements
array_reduce()Combine into one value
array_walk(), array_walk_recursive()Apply a callback in place
array_reverse()Reverse order
array_count_values()Count occurrences of each value

Searching

FunctionPurpose
in_array(), array_search()Find a value
array_find(), array_find_key()First element matching a callback (PHP 8.4+)
array_any(), array_all()Any / all elements match (PHP 8.4+)
preg_grep()Values matching a regular expression

Sorting

sort(), rsort(), asort(), arsort(), ksort(), krsort(), usort(), uasort(), uksort(), natsort(), natcasesort(), array_multisort(), shuffle() — see Sorting Arrays.

Calculating

FunctionPurpose
array_sum() / array_product()Sum / product of values
max() / min()Largest / smallest value

Generating

FunctionPurpose
range()Sequence of numbers or letters
array_fill()Repeated value
array_rand($array, $n)Random key(s) (not cryptographically secure)
iterator_to_array()Convert an iterator or generator to an array
compact() / extract()Variables ↔ array (use with care)

Selected Functions in Detail

array_chunk() — Split Into Groups

<?php
print_r(array_chunk(range(1, 7), 3));

Output

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )
    [2] => Array
        (
            [0] => 7
        )
)

The last chunk may be smaller. Passing true as the third argument preserves the original keys. Typical uses: paginating results, building grid rows (three products per row), and sending data to an API in batches.

array_count_values() — Count Occurrences

<?php
$votes = ['php', 'js', 'php', 'go', 'php', 'js'];
$counts = array_count_values($votes);
arsort($counts);
print_r($counts);

Output

Array
(
    [php] => 3
    [js] => 2
    [go] => 1
)

Values become keys, and counts become values. It works for strings and integers.

array_flip() — Swap Keys and Values

<?php
$codes = ['IN' => 'India', 'JP' => 'Japan'];
print_r(array_flip($codes));

Output

Array
(
    [India] => IN
    [Japan] => JP
)

Use it to create reverse lookups or to turn a list into a set for fast isset() checks. Duplicate values collapse into one key (the last one wins).

array_intersect() and array_diff() — Set Operations

<?php
$required = ['php', 'mysql', 'git', 'linux'];
$candidate = ['php', 'git', 'docker'];
$matching = array_values(array_intersect($required, $candidate));
$missing = array_values(array_diff($required, $candidate));
echo "Matching skills: " . implode(', ', $matching) . "\n";
echo "Missing skills: " . implode(', ', $missing) . "\n";

Output

Matching skills: php, git
Missing skills: mysql, linux

Both functions preserve the keys of the first array, so array_values() re-indexes the results. The _key and _assoc variants compare keys or key–value pairs instead of values.

array_slice() — Extract a Portion

<?php
$leaderboard = ['Charu', 'Asha', 'Dev', 'Bala', 'Esha'];
echo "Top 3: " . implode(', ', array_slice($leaderboard, 0, 3)) . "\n";
echo "Last 2: " . implode(', ', array_slice($leaderboard, -2)) . "\n";
echo "Original count: " . count($leaderboard) . "\n";

Output

Top 3: Charu, Asha, Dev
Last 2: Bala, Esha
Original count: 5

Unlike array_splice(), array_slice() does not modify the original array.

array_walk_recursive() — Apply a Callback to Every Leaf Value

<?php
$formData = [
    'name' => '  Asha ',
    'address' => ['city' => ' Chennai ', 'pin' => ' 600042 '],
];
array_walk_recursive($formData, function (mixed &$value): void {
    if (is_string($value)) {
        $value = trim($value);
    }
});
echo json_encode($formData) . "\n";

Output

{"name":"Asha","address":{"city":"Chennai","pin":"600042"}}

array_walk_recursive() visits every non-array value at any depth. The callback receives each value by reference (&$value), so it can modify the array in place — here, trimming every submitted field.

array_is_list() — Is It a Proper List? (PHP 8.1+)

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

Output

bool(true)
bool(false)
bool(false)
bool(true)

Useful before json_encode() (a list becomes a JSON array; anything else becomes a JSON object) and for validating input that must be a simple list.

extract() — Use With Caution

extract($array) creates variables from array keys. On untrusted data (such as $_POST), it lets attackers overwrite any variable in scope, which is a serious security risk. Read the keys you need explicitly instead (see Variable Variables).


Practical Example: Paginating a List

<?php
function paginate(array $items, int $perPage, int $page): array
{
    $pages = array_chunk($items, $perPage);
    $totalPages = max(1, count($pages));
    $page = max(1, min($page, $totalPages));
    return [
        'items' => $pages[$page - 1] ?? [],
        'page' => $page,
        'totalPages' => $totalPages,
    ];
}
$products = array_map(fn(int $n): string => "Product $n", range(1, 7));
$result = paginate($products, 3, 2);
echo "Page {$result['page']} of {$result['totalPages']}: " . implode(', ', $result['items']) . "\n";
$last = paginate($products, 3, 99);
echo "Page {$last['page']} of {$last['totalPages']}: " . implode(', ', $last['items']) . "\n";

Output

Page 2 of 3: Product 4, Product 5, Product 6
Page 3 of 3: Product 7

Step-by-Step Explanation

  1. range() and array_map() generate seven product names.
  2. array_chunk() splits them into pages of three: [1–3], [4–6], [7].
  3. The requested page is clamped into the valid range with max() and min(), so page 99 becomes the last page.
  4. $pages[$page - 1] ?? [] selects the page (pages are numbered from 1, array indexes from 0) and returns an empty list if there are no items. For data stored in a database, paginate with LIMIT and OFFSET in the query instead of loading everything into an array (see Pagination with PHP and MySQL).

Common Mistakes

Assuming a Function Modifies the Array

Effect: array_reverse($list); alone does nothing visible. Fix: Assign the result: $list = array_reverse($list);.

Assuming a Function Returns the Array

Effect: $sorted = sort($list); stores true. Fix: Call in-place functions as statements, then use the original variable.

Ignoring Key Preservation

Effect: Gaps after array_filter(), array_diff(), or array_unique(); lost keys after array_merge() or sort(). Fix: Check how each function treats keys; use array_values() or key-preserving variants as needed.

Re-implementing Built-in Functions

Effect: More code and more bugs. Fix: Search this reference (or the manual) before writing a loop for a common task.


Best Practices

  • Learn the categories; look up exact signatures in the manual when needed.
  • Prefer functions that return new arrays for clearer, side-effect-free code.
  • Pay attention to key preservation and strict comparison options.
  • Use PHP 8.4+ functions (array_find(), array_any(), array_all()) and PHP 8.5+ functions (array_first(), array_last()) when your project's PHP version allows.
  • Process large datasets in the database, and use array functions on the results. Official reference: https://www.php.net/manual/en/ref.array.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PHP XML Parsers PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions What Are Superglobals? $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE
Ask about this post
AI Ask about this post

Ask questions about Array Functions and get answers drawn from it.

Signed-in readers only.