PHP array_map() Function
October 29, 2020
Hello dear readers! welcome back to another section of our tutorial on PHP. In this tutorial, we will be studying about the PHP Function array_map().
PHP array_map() function returns an array containing all of the elements of array1 after applying the callback function to each of them.
PHP array_map() function returns an array containing all of the elements of array1 after applying the callback function to each of them.
Syntax
Following below is the syntax to use this function -
array array_map ( callback $callback, array $array1 [, array $array2...] );
Parameter Details
Sr.No | Parameter & Description |
---|---|
1 | callback(Required) The name of the user-made function, or null. |
2 | array1(Required) It specifies an array. |
3 | array2(Optional) It specifies an array. |
4 | array3(Optional) It specifies an array. |
Return Value
It returns an array, containing all the elements of array1.
Example
Try out the below example -
<?php function cube($n) { return($n * $n * $n); } $input = array(1, 2, 3, 4, 5); $result = array_map("cube", $input); print_r($result); ?>
Output
When the above code is executed, it will produce the following result -
Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )
Example2
Try out the below example using multiple arrays -
<?php function call_back_func($v1, $v2) { if ($v1 === $v2) { return "equal"; } return "different"; } $array1 = array(1, 2, 3, 4); $array2 = array(10, 2, 30, 4); $b = array_map("call_back_func", $array1, $array2); print_r($b); ?>
Output
When the above code is executed, it will produce the following result -
Array ( [0] => different [1] => equal [2] => different [3] => equal )
READ: PHP Regular Expressions
Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial, we will discuss about the array_merge() Function in PHP.
Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.
Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.