π οΈ PHP Array Functions β Complete Guide
Index: Functions Index | Parent: Array Index
1. Transform Functions
array_map() β Apply a function to every element
When to use: You want to transform every element and get a new array back.
// Basic usage
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
// [2, 4, 6, 8, 10]
// Real Laravel example: format prices
$products = [100, 200, 300];
$formatted = array_map(fn($p) => '$' . number_format($p, 2), $products);
// ['$100.00', '$200.00', '$300.00']
// Multiple arrays
$a = [1, 2, 3];
$b = [10, 20, 30];
$sum = array_map(fn($x, $y) => $x + $y, $a, $b);
// [11, 22, 33]
JavaScript equivalent:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
Laravel Collection equivalent:
$collection->map(fn($item) => $item->name);
array_walk() β Modify array in-place (no new array)
When to use: You want to modify the original array in place without creating a new one.
$prices = ['apple' => 1.50, 'banana' => 0.75, 'cherry' => 2.00];
array_walk($prices, function (&$price, $key) {
$price = '$' . number_format($price, 2);
});
// ['apple' => '$1.50', 'banana' => '$0.75', 'cherry' => '$2.00']
map vs walk:
array_mapreturns new array.array_walkmodifies in-place.
2. Filter Functions
array_filter() β Keep elements that pass a test
When to use: Remove unwanted elements based on a condition.
// Basic: remove falsy values (null, 0, '', false)
$arr = [0, 1, '', 'hello', null, false, 42];
$filtered = array_values(array_filter($arr));
// [1, 'hello', 42]
// With callback
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evens = array_values(array_filter($numbers, fn($n) => $n % 2 === 0));
// [2, 4, 6, 8, 10]
// Laravel: filter active users
$users = [
['name' => 'Alice', 'active' => true],
['name' => 'Bob', 'active' => false],
['name' => 'Carol', 'active' => true],
];
$activeUsers = array_values(array_filter($users, fn($u) => $u['active']));
// Alice, Carol only
// Filter with ARRAY_FILTER_USE_KEY (filter by key)
$data = ['name' => 'Alice', 'password' => 'secret', 'age' => 25];
$safe = array_filter($data, fn($key) => $key !== 'password', ARRAY_FILTER_USE_KEY);
// ['name' => 'Alice', 'age' => 25]
JavaScript equivalent:
const evens = numbers.filter(n => n % 2 === 0);
Laravel Collection equivalent:
$collection->filter(fn($item) => $item->active);
β οΈ Always use
array_values()afterarray_filter()to re-index!
3. Reduce Functions
array_reduce() β Collapse array to a single value
When to use: Calculate a single result from all elements (sum, product, build string, count conditions).
// Sum
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item, 0);
// 15
// Product
$product = array_reduce($numbers, fn($carry, $item) => $carry * $item, 1);
// 120
// Max value
$max = array_reduce($numbers, fn($carry, $item) => max($carry, $item), PHP_INT_MIN);
// 5
// Build a string
$words = ['Hello', 'World', 'PHP'];
$sentence = array_reduce($words, fn($carry, $item) => $carry . ' ' . $item, '');
// ' Hello World PHP'
// Count where condition is true
$scores = [45, 82, 91, 38, 76, 55];
$passing = array_reduce($scores, fn($carry, $score) => $score >= 60 ? $carry + 1 : $carry, 0);
// 3 (scores >= 60)
// Group by (advanced)
$orders = [
['status' => 'pending', 'amount' => 100],
['status' => 'completed', 'amount' => 200],
['status' => 'pending', 'amount' => 150],
];
$grouped = array_reduce($orders, function($carry, $order) {
$carry[$order['status']][] = $order;
return $carry;
}, []);
// ['pending' => [...], 'completed' => [...]]
JavaScript equivalent:
const sum = numbers.reduce((carry, item) => carry + item, 0);
Laravel Collection equivalent:
$collection->reduce(fn($carry, $item) => $carry + $item->amount, 0);
// or shorthand:
$collection->sum('amount');
4. Search Functions
in_array() β Check if value exists
$fruits = ['apple', 'banana', 'cherry'];
// Loose comparison (default)
in_array('banana', $fruits); // true
in_array('grape', $fruits); // false
// STRICT comparison (recommended β checks type too)
$numbers = [1, 2, 3, '4', 5];
in_array(4, $numbers); // true (loose: '4' == 4)
in_array(4, $numbers, true); // false (strict: '4' !== 4)
in_array('4', $numbers, true); // true
β οΈ Always use third parameter
truefor strict comparison!
array_search() β Find the KEY of a value
$fruits = ['apple', 'banana', 'cherry'];
$key = array_search('banana', $fruits); // 1
$key = array_search('grape', $fruits); // false
// With associative array
$users = ['alice' => 101, 'bob' => 102, 'carol' => 103];
$key = array_search(102, $users); // 'bob'
array_key_exists() vs isset()
$data = ['name' => 'Alice', 'age' => null];
array_key_exists('age', $data); // true (key exists even if null)
isset($data['age']); // false (isset returns false for null)
isset($data['name']); // true
// Rule: use array_key_exists when null is a valid value
// use isset for performance and when null means "not set"
5. Sort Functions
| Function | What it does | Preserves Keys? |
|---|---|---|
sort() | Sort ascending | β Re-indexes |
rsort() | Sort descending | β Re-indexes |
asort() | Sort values ascending | β Keeps keys |
arsort() | Sort values descending | β Keeps keys |
ksort() | Sort by key ascending | β |
krsort() | Sort by key descending | β |
usort() | Sort with custom comparator | β Re-indexes |
uasort() | Custom comparator | β Keeps keys |
uksort() | Custom comparator on keys | β |
// sort() β simple ascending
$arr = [3, 1, 4, 1, 5, 9];
sort($arr);
// [1, 1, 3, 4, 5, 9]
// usort() β custom sort (most powerful)
$users = [
['name' => 'Charlie', 'age' => 30],
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 28],
];
// Sort by age ascending
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
// Sort by name alphabetically
usort($users, fn($a, $b) => $a['name'] <=> $b['name']);
// Sort by age DESC, then name ASC (multi-key)
usort($users, function($a, $b) {
if ($a['age'] !== $b['age']) {
return $b['age'] <=> $a['age']; // age DESC
}
return $a['name'] <=> $b['name']; // name ASC
});
The spaceship operator <=>:
// $a <=> $b returns:
// -1 if $a < $b
// 0 if $a == $b
// 1 if $a > $b
JavaScript equivalent:
users.sort((a, b) => a.age - b.age); // ascending
users.sort((a, b) => b.age - a.age); // descending
6. Merge & Combine
array_merge() β Combine arrays
$a = [1, 2, 3];
$b = [4, 5, 6];
$merged = array_merge($a, $b);
// [1, 2, 3, 4, 5, 6]
// With associative (later keys overwrite earlier)
$defaults = ['color' => 'red', 'size' => 'M'];
$custom = ['color' => 'blue', 'weight' => 'heavy'];
$result = array_merge($defaults, $custom);
// ['color' => 'blue', 'size' => 'M', 'weight' => 'heavy']
// Spread operator (PHP 7.4+)
$merged = [...$a, ...$b];
array_combine() β Create key-value pairs from two arrays
$keys = ['name', 'age', 'city'];
$values = ['Alice', 25, 'NYC'];
$combined = array_combine($keys, $values);
// ['name' => 'Alice', 'age' => 25, 'city' => 'NYC']
7. Slice & Splice
array_slice() β Extract a portion (non-destructive)
$arr = [1, 2, 3, 4, 5, 6, 7];
// array_slice($arr, $start, $length, $preserve_keys)
$slice = array_slice($arr, 2, 3); // [3, 4, 5]
$slice = array_slice($arr, -3); // [5, 6, 7] (last 3)
$slice = array_slice($arr, 1, 3, true); // [1=>2, 2=>3, 3=>4] (preserve keys)
// Laravel: paginate manually
$page = 2;
$perPage = 3;
$paged = array_slice($arr, ($page - 1) * $perPage, $perPage);
// page 2 of 3: [4, 5, 6]
array_splice() β Remove AND/OR insert (destructive)
$arr = [1, 2, 3, 4, 5];
// Remove 2 elements starting at index 1
$removed = array_splice($arr, 1, 2);
// $arr = [1, 4, 5], $removed = [2, 3]
// Insert at index 2 (remove 0 elements)
$arr = [1, 2, 3, 4, 5];
array_splice($arr, 2, 0, [10, 11]);
// $arr = [1, 2, 10, 11, 3, 4, 5]
// Replace elements
$arr = [1, 2, 3, 4, 5];
array_splice($arr, 1, 2, [20, 30]);
// $arr = [1, 20, 30, 4, 5]
8. Math Functions
$numbers = [1, 2, 3, 4, 5];
array_sum($numbers); // 15
array_product($numbers); // 120
count($numbers); // 5
max($numbers); // 5
min($numbers); // 1
// count_values β frequency count
$fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
array_count_values($fruits);
// ['apple' => 3, 'banana' => 2, 'cherry' => 1]
// array_fill β fill with value
$zeros = array_fill(0, 5, 0); // [0, 0, 0, 0, 0]
$filled = array_fill(0, 3, 'x'); // ['x', 'x', 'x']
// range β generate sequences
range(1, 5); // [1, 2, 3, 4, 5]
range(0, 10, 2); // [0, 2, 4, 6, 8, 10]
range('a', 'e'); // ['a', 'b', 'c', 'd', 'e']
9. Set Operations
$a = [1, 2, 3, 4, 5];
$b = [3, 4, 5, 6, 7];
// Unique elements
array_unique([1, 2, 2, 3, 3]); // [0=>1, 1=>2, 3=>3] β use array_values!
// Difference: elements in $a NOT in $b
array_diff($a, $b); // [1, 2]
// Intersection: elements in BOTH
array_intersect($a, $b); // [3, 4, 5]
// Key-based diff/intersect
array_diff_key($a, $b);
array_intersect_key($a, $b);
10. Laravel Collection Equivalents
| PHP Function | Laravel Collection | JavaScript |
|---|---|---|
array_map | ->map() | .map() |
array_filter | ->filter() | .filter() |
array_reduce | ->reduce() | .reduce() |
in_array | ->contains() | .includes() |
usort | ->sortBy() | .sort() |
array_unique | ->unique() | [...new Set()] |
array_merge | ->merge() | [...a, ...b] |
array_slice | ->slice() | .slice() |
array_sum | ->sum() | .reduce((a,b)=>a+b, 0) |
array_keys | ->keys() | Object.keys() |
array_values | ->values() | Object.values() |
array_count_values | ->countBy() | β |
array_chunk | ->chunk() | β |
array_column | ->pluck() | .map(x=>x.field) |
Laravel Collection example:
$users = collect(User::all());
$result = $users
->filter(fn($u) => $u->active)
->map(fn($u) => ['name' => $u->name, 'email' => $u->email])
->sortBy('name')
->values();
11. When to Use What β Decision Table
| You want to... | Use this | Example |
|---|---|---|
| Transform every element | array_map / ->map() | double all prices |
| Remove unwanted elements | array_filter / ->filter() | keep active users |
| Get one result from all | array_reduce / ->reduce() | total sum |
| Check if value exists | in_array() / ->contains() | is 'admin' in roles? |
| Find where value is | array_search() | find index of value |
| Check if key exists | array_key_exists() | has 'email' key? |
| Sort by custom rule | usort() / ->sortBy() | sort by age desc |
| Get part of array | array_slice() / ->slice() | pagination |
| Combine two arrays | array_merge() / ->merge() | merge defaults |
| Count element frequency | array_count_values() / ->countBy() | word frequency |
| Remove duplicates | array_unique() / ->unique() | dedup list |
| Get field from objects | array_column() / ->pluck() | all user emails |
| Split into groups | array_chunk() / ->chunk() | batch processing |
Interview Questions β PHP Array Functions
Q1. Flatten a nested array [M][FB]
Question: Given [1, [2, 3], [4, [5, 6]]], return [1, 2, 3, 4, 5, 6]
π§ How to Approach This
Step 1 β Recognize the pattern:
Nested structure of arbitrary depth = recursion.
Step 2 β Brute force:
Keep applying
array_merge(...$arr)in a loop until no nested arrays remain β multiple passes, messy.Step 3 β Optimal:
Walk recursively. For each element: if it's an array, recurse; if it's a value, add to result.
Step 4 β PHP built-in:
array_walk_recursivewalks every leaf value automatically. Simplest approach.Step 5 β Edge cases:
- Already flat: works correctly, just copies values
- Empty nested arrays: ignored
Way of Thinking:
Recursion. Loop through each element β if it's an array, recurse into it. Merge results.
// PHP 5.6+ one-liner for 1 level deep:
$flat = array_merge(...$nestedArray);
// Fully recursive (any depth):
function flattenArray(array $arr): array {
$result = [];
array_walk_recursive($arr, function($item) use (&$result) {
$result[] = $item;
});
return $result;
}
// Manual recursive:
function flattenManual(array $arr): array {
$result = [];
foreach ($arr as $item) {
if (is_array($item)) {
$result = array_merge($result, flattenManual($item));
} else {
$result[] = $item;
}
}
return $result;
}
print_r(flattenManual([1, [2, 3], [4, [5, 6]]]));
// [1, 2, 3, 4, 5, 6]
JavaScript:
[1, [2, 3], [4, [5, 6]]].flat(Infinity);
// [1, 2, 3, 4, 5, 6]
Q2. Group array by key [M][FB][L]
Question: Group users by their role.
π§ How to Approach This
Step 1 β Recognize the pattern:
Group by = hashmap where key is the grouping field, value is array of items.
Step 2 β Algorithm:
One pass through the array. For each item: append to
$grouped[$item['role']].PHP auto-creates the key as an array on first access.
Step 3 β Laravel context:
collect($items)->groupBy('role')does exactly this. Mention both in interviews.Step 4 β Edge cases:
- Items with null/missing key: handle with
$item['role'] ?? 'unknown'
Way of Thinking:
Use
array_reducewith grouped associative array, orusort+ split. In Laravel use->groupBy().
$users = [
['name' => 'Alice', 'role' => 'admin'],
['name' => 'Bob', 'role' => 'user'],
['name' => 'Carol', 'role' => 'admin'],
['name' => 'Dave', 'role' => 'user'],
];
// Manual (PHP)
$grouped = [];
foreach ($users as $user) {
$grouped[$user['role']][] = $user;
}
// Using array_reduce
$grouped = array_reduce($users, function($carry, $user) {
$carry[$user['role']][] = $user;
return $carry;
}, []);
// Laravel Collection
$grouped = collect($users)->groupBy('role');
Q3. Find second largest number [M][FB]
π§ How to Approach This
Step 1 β Simple approach:
Deduplicate, sort descending, take index 1. O(n log n). Acceptable in most interviews.
Step 2 β Optimal: single pass O(n):
Track
maxandsecondMaxseparately. If num > max: secondMax = max, max = num. Else if num > secondMax and num != max: secondMax = num.Step 3 β Edge cases:
- Less than 2 unique values: throw exception or return null
- All same values: no second largest exists
Way of Thinking:
Sort descending, take index 1. OR: single pass β track max and secondMax separately.
function secondLargest(array $arr): int {
$arr = array_unique($arr); // remove duplicates
rsort($arr);
return $arr[1] ?? throw new \InvalidArgumentException('Need at least 2 unique values');
}
// O(n) single pass β better approach
function secondLargestFast(array $arr): int {
$max = $secondMax = PHP_INT_MIN;
foreach ($arr as $num) {
if ($num > $max) {
$secondMax = $max;
$max = $num;
} elseif ($num > $secondMax && $num !== $max) {
$secondMax = $num;
}
}
return $secondMax;
}
echo secondLargestFast([3, 1, 4, 1, 5, 9, 2, 6]); // 6
Q4. Transpose a 2D matrix [M]
Question: Convert rows to columns.
Input: Output:
[1, 2, 3] [1, 4, 7]
[4, 5, 6] β [2, 5, 8]
[7, 8, 9] [3, 6, 9]
π§ How to Approach This
Step 1 β Recognize the pattern:
Transpose swaps row index and column index:
result[j][i] = matrix[i][j].Step 2 β Algorithm:
Two nested loops. Outer loop over rows (i), inner loop over columns (j). Assign
result[j][i] = matrix[i][j].Step 3 β PHP one-liner:
array_map(null, ...$matrix)transposes using zip behavior of array_map.Step 4 β Edge cases:
- Non-square matrix: outer loop should be rows, inner should be cols (not rows)
- Empty matrix: return empty
Way of Thinking:
$result[$j][$i] = $matrix[$i][$j]β swap row and column indices.
function transpose(array $matrix): array {
$result = [];
for ($i = 0; $i < count($matrix); $i++) {
for ($j = 0; $j < count($matrix[$i]); $j++) {
$result[$j][$i] = $matrix[$i][$j];
}
}
return $result;
}
// PHP one-liner
$transposed = array_map(null, ...$matrix);
// JavaScript
const transposed = matrix[0].map((_, i) => matrix.map(row => row[i]));
Q5. Merge and deduplicate two sorted arrays [M][FB]
π§ How to Approach This
Step 1 β Recognize the pattern:
Two sorted arrays + merge in order = two-pointer merge (like merge step of merge sort).
Step 2 β Brute force:
Concatenate, sort, deduplicate β O(n log n). But we can do O(n) because arrays are already sorted.
Step 3 β Optimal: two-pointer merge:
i=0, j=0. Compare heads: take smaller, advance that pointer. On equal: take one, advance both (deduplication).
Step 4 β Edge cases:
- One array exhausted: copy remainder of the other
- All elements equal: result has just one element
Way of Thinking:
Two pointers β compare heads of both arrays, take the smaller, advance that pointer. Skip duplicates.
function mergeSortedArrays(array $a, array $b): array {
$result = [];
$i = $j = 0;
while ($i < count($a) && $j < count($b)) {
if ($a[$i] < $b[$j]) {
$result[] = $a[$i++];
} elseif ($a[$i] > $b[$j]) {
$result[] = $b[$j++];
} else {
$result[] = $a[$i++]; // equal: take one, skip both
$j++;
}
}
while ($i < count($a)) $result[] = $a[$i++];
while ($j < count($b)) $result[] = $b[$j++];
return $result;
}
print_r(mergeSortedArrays([1, 3, 5, 7], [2, 3, 6, 8]));
// [1, 2, 3, 5, 6, 7, 8]