PHP array_map() Function

PHP array_map() Function


Hello folks! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP array_map() Function.

The built-in array_map() function returns an array containing all 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.NoParameter & 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

This function 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 )


Alright guys! This is where we are going to be rounding up for this tutorial post. In our next tutorial, we are going to be discussing about the PHP array_merge() Function.

Feel free to ask your questions where necessary and we 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.