In PHP, the array_map()
function is a powerful tool for manipulating arrays. It takes an array and a callback function as parameters, applies the callback function to each element of the array, and returns a new array with the modified values.
Basic Usage
Here’s a simple example of using array_map()
:
<?php function square($n) { return $n * $n; } $numbers = array(1, 2, 3, 4, 5); $squares = array_map("square", $numbers); print_r($squares); ?>
In this example, we define a function called square()
that takes a number and returns its square. We then create an array of numbers and pass it to array_map()
along with the square()
function as the callback.
array_map()
applies the square()
function to each element of the array and returns a new array with the squared values. The output of the above code would be:
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
Multiple Arrays
array_map()
can also take multiple arrays as input. Here’s an example:
<?php function add($a, $b) { return $a + $b; } $a = array(1, 2, 3); $b = array(4, 5, 6); $c = array_map("add", $a, $b); print_r($c); ?>
In this example, we define a function called add()
that takes two numbers and returns their sum. We then create two arrays of numbers and pass them to array_map()
along with the add()
function as the callback.
array_map()
applies the add()
function to each corresponding element of the arrays and returns a new array with the summed values. The output of the above code would be:
Array ( [0] => 5 [1] => 7 [2] => 9 )
Using Anonymous Functions
In some cases, it may be more convenient to use anonymous functions (also known as closures) instead of named functions. Here’s an example:
<?php $numbers = array(1, 2, 3, 4, 5); $squares = array_map(function($n) { return $n * $n; }, $numbers); print_r($squares); ?>
In this example, we create an anonymous function that takes a number and returns its square. We then pass the anonymous function to array_map()
instead of a named function.
array_map()
applies the anonymous function to each element of the array and returns a new array with the squared values. The output of the above code would be the same as the first example:
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
Conclusion
The array_map()
function is a powerful tool for manipulating arrays in PHP. It allows you to apply a callback function to each element of an array and return a new array with the modified values. With the ability to take multiple arrays as input and use anonymous functions, array_map()
is a versatile function that you’ll find yourself using frequently.
We hope this article has been helpful in explaining how array_map()
works and giving you some ideas for how you can use it in your own code. Happy coding!
[…] the above code, we first define an array of numbers. We then use the array_map() function to apply a callback function to each element of the array. The callback function simply […]