Working with arrays in PHP? These functions can save you time, reduce code, and improve performance.
PHP offers a powerful set of built-in array functions that make your life as a developer easier. Whether you're manipulating data, filtering values, or transforming structures — these are the most useful PHP array functions you should master.
1️⃣ array_map()
Applies a callback function to every item in the array.
$numbers = [1, 2, 3];
$squares = array_map(fn($n) => $n * $n, $numbers);
// [1, 4, 9]
2️⃣ array_filter()
Filters values based on a condition.
$numbers = [1, 2, 3, 4];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
// [2, 4]
3️⃣ array_reduce()
Reduces an array to a single value.
$numbers = [1, 2, 3];
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item, 0);
// 6
4️⃣ array_merge()
Merges two or more arrays into one.
$a = [1, 2];
$b = [3, 4];
$result = array_merge($a, $b);
// [1, 2, 3, 4]
5️⃣ array_keys() and array_values()
Extract all the keys or values from an array.
$data = ['name' => 'John', 'age' => 30];
$keys = array_keys($data); // ['name', 'age']
$values = array_values($data); // ['John', 30]
6️⃣ in_array() and array_search()
Check if a value exists or find the index/key of a value.
$colors = ['red', 'green', 'blue'];
in_array('green', $colors); // true
array_search('blue', $colors); // 2
7️⃣ array_slice()
Extract a portion of an array.
$data = [10, 20, 30, 40];
$slice = array_slice($data, 1, 2);
// [20, 30]
8️⃣ array_unique()
Remove duplicate values from an array.
$data = [1, 2, 2, 3];
$unique = array_unique($data);
// [1, 2, 3]
9️⃣ array_column()
Extract a single column of values from a multidimensional array.
$users = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
];
$names = array_column($users, 'name');
// ['Alice', 'Bob']
🔟 array_combine()
Creates an associative array from two arrays (keys and values).
$keys = ['name', 'age'];
$values = ['Jane', 25];
$user = array_combine($keys, $values);
// ['name' => 'Jane', 'age' => 25]
Final Thoughts
Working with arrays is a core part of PHP development, and mastering these built-in functions can significantly boost your productivity. Functions like array_map()
, array_filter()
, and array_column()
not only simplify complex logic but also make your code more readable and maintainable.
If you have a favorite array function not listed here, or a clever way to use one, feel free to share it in the comments below!
Top comments (0)