PHP Array Functions
PHP ships with ~80 array functions. Memorise the ones below; look the rest up when you need them.
Size & basics
| Function | Returns |
|---|---|
count($arr) | Number of elements. |
array_keys($arr) / array_values($arr) | Just the keys / values. |
array_key_exists($k, $arr) | True if key is defined. |
in_array($needle, $arr, strict: true) | Membership test. |
array_search($needle, $arr) | First key with that value, or false. |
Transform
PHP
$nums = [1, 2, 3, 4]; array_map(fn($n) => $n * 2, $nums); // [2, 4, 6, 8] array_filter($nums, fn($n) => $n > 2); // [2 => 3, 3 => 4] array_reduce($nums, fn($c, $n) => $c + $n, 0); // 10 array_sum($nums); // 10 array_product($nums); // 24
Combine
| Function | Does |
|---|---|
array_merge($a, $b) | Concatenate; string keys overwrite. |
array_combine($keys, $values) | Build a dict. |
array_flip($arr) | Swap keys ↔ values. |
array_unique($arr) | Dedup, preserving first occurrence. |
array_diff / array_intersect | Set difference / intersection. |
Splitting & joining strings
PHP
explode(',', 'a,b,c'); // ['a', 'b', 'c']
implode('-', ['a', 'b']); // 'a-b'
Higher-order patterns
PHP
$users = [
['id' => 1, 'name' => 'Ada'],
['id' => 2, 'name' => 'Linus'],
];
// Pluck a column
$names = array_column($users, 'name'); // ['Ada', 'Linus']
// Re-key by id
$byId = array_column($users, null, 'id'); // [1 => [...], 2 => [...]]
Tip: When you spot a manual
foreach that's filtering and re-keying an array, array_column or array_combine probably does it in one line.Example
Example
<?php $nums = [3, 1, 4, 1, 5, 9, 2]; echo count($nums), PHP_EOL; echo array_sum($nums), PHP_EOL; print_r(array_unique($nums)); print_r(array_filter($nums, fn($n) => $n > 2));Try it Yourself »
Exercise
Pluck a single column from an array of rows.
($users, 'name')
Snake_case; 12 chars.
Discussion
Loading…