Arrays are one of the most commonly used data structures in PHP, and PHP provides a vast array of built-in functions to manipulate them efficiently. In this article, we’ll explore the five most useful array functions that every PHP developer should know.

1. array_map()

The array_map() function applies a callback function to each element of an array and returns a new array with the modified values.

Example:

function square($num) {
return $num * $num;
}
$numbers = [1, 2, 3, 4, 5];
$squaredNumbers = array_map('square', $numbers);
print_r($squaredNumbers);

Output:

Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

2. array_filter()

The array_filter() function filters elements of an array using a callback function.

Example:

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evenNumbers = array_filter($numbers, function($num) {
return $num % 2 == 0;
});
print_r($evenNumbers);

Output:

Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )

3. array_reduce()

The array_reduce() function reduces an array to a single value by applying a callback function iteratively.

Example:

$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sum;

Output:

15

4. array_merge()

The array_merge() function merges two or more arrays into one.

Example:

$array1 = ["a" => "Apple", "b" => "Banana"];
$array2 = ["c" => "Cherry", "d" => "Date"];
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);

Output:

Array ( [a] => Apple [b] => Banana [c] => Cherry [d] => Date )

5. array_unique()

The array_unique() function removes duplicate values from an array.

Example:

$numbers = [1, 2, 2, 3, 4, 4, 5];
$uniqueNumbers = array_unique($numbers);
print_r($uniqueNumbers);

Output:

Array ( [0] => 1 [1] => 2 [3] => 3 [4] => 4 [6] => 5 )

Conclusion

These five array functions — array_map(), array_filter(), array_reduce(), array_merge(), and array_unique()—are incredibly powerful for handling and manipulating arrays efficiently. Mastering them will enhance your PHP development skills and improve your coding efficiency.

Which array function do you use the most? Let me know in the comments!