Array Functions
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
- Most functions return a new array and leave the input unchanged:
array_map(),array_filter(),array_merge(),array_slice(),array_reverse(), and others. - 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(). - 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. - Comparison mode: search functions compare loosely unless you pass
truefor strict mode (in_array(),array_search(),array_keys()).
Reference by Category
Inspecting
| Function | Purpose |
|---|---|
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
| Function | Purpose |
|---|---|
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
| Function | Purpose |
|---|---|
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
| Function | Purpose |
|---|---|
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
| Function | Purpose |
|---|---|
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
| Function | Purpose |
|---|---|
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
| Function | Purpose |
|---|---|
array_sum() / array_product() | Sum / product of values |
max() / min() | Largest / smallest value |
Generating
| Function | Purpose |
|---|---|
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
range()andarray_map()generate seven product names.array_chunk()splits them into pages of three:[1–3],[4–6],[7].- The requested page is clamped into the valid range with
max()andmin(), so page99becomes the last page. $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 withLIMITandOFFSETin 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