Array Functions

Yo Yogesh.M Updated 29 Oct 2026
7 min read

Array Functions

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.

Data Mining
Introduction to Data Mining Data Mining Implementation Process Data Mining Architecture Data Mining Techniques KDD: Knowledge Discovery in Databases History of Data Mining Data Mining Tools Data Mining vs Machine Learning Facebook Data Mining Social Media Data Mining Methods Clustering in Data Mining Text Data Mining Bagging vs Boosting Data Mining vs Data Warehousing Social Media Data Mining Data Mining: Bayesian Classifiers Data Mining: World Wide Web Different Types of Clustering Bitcoin Mining and Blockchain Data Mining Orange Data Mining Data Mining vs Big Data Decision Tree Induction Educational Data Mining Data Mining in Healthcare Apriori Algorithm Data Integration in Data Mining Difference Between Data Mining and Text Mining Discretization in Data Mining Redundancy and Correlation in Data Mining Classification of Data Mining Systems Classification Algorithms in Data Mining Data Generalization in Data Mining Classification and Prediction in Data Mining Regression in Data Mining What Is an Outlier in Data Mining Data Cleaning in Data Mining Data Processing in Data Mining Data Mining Task Primitives Web Content Mining, Web Structure Mining, and Web Usage Mini Binning in Data Mining KDD vs. Data Mining Noise in Data Mining BIRCH in Data Mining Stemming in Data Mining Feature Transformation in Data Mining Visual and Audio Data Mining Class Comparison Methods in Data Mining Data Selection in Data Mining Tasks and Functionalities of Data Mining Ubiquitous and Invisible Data Mining Importance of Data Mining Data Quality in Data Mining Mining Frequent Patterns in Data Mining Data Warehouse and OLAP Technology for Data Mining Need for Data Mining Pattern Evaluation Methods in Data Mining Logarithms and Exponents in Complexity Analysis Time Series Clustering What is the C4.5 Algorithm and How Does It Work? Expanding Contractions in Text Mining Cosine Similarity in Data Mining Lazy Learning in Data Mining Neural Networks in Data Mining Building a Text Normalizer Shallow Parsing Data Pipeline Orchestration Big Data vs Small Data Myths of Data Mining Data Reduction in Data Mining Data Mining Models Difference Between Data Mining and Data Science Difference Between Data Mining and Statistics Difference Between Data Mining and Web Mining Difference Between Data Mining and Data Analysis Difference Between Business Intelligence and Data Mining Difference Between Data Mining and Data Visualization Data Mining vs Data Analytics Types of Data Mining Difference Between Data Profiling and Data Mining Predictive Analytics vs Data Mining Difference Between Data Mining and OLAP Descriptive and Predictive Data Mining Difference Between Spatial and Temporal Data Mining Difference Between Classification and Clustering in Data Min Hierarchical Clustering in Data Mining Density-Based Clustering in Data Mining What Is Aggregation in Data Mining?
Ask about this post
AI Ask about this post

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

Signed-in readers only.