PHP - Function array_map()


Advertisements


Syntax

array array_map ( callback $callback, array $array1 [, array $array2...] );

Definition and Usage

It returns an array containing all the elements of array1 after applying the callback function to each one.

Parameters

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 Values

It returns an array containing all the processed elements of array1.

Example

Try out following example −

Live Demo
<?php
   function cube($n) {
      return($n * $n * $n);
   }
   
   $input = array(1, 2, 3, 4, 5);
   $result = array_map("cube", $input);
   
   print_r($result);
?> 

This will produce the following result −

Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )

Using multiple arrays.

Live Demo
<?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);

?>

This will produce the following result −

Array ( [0] => different [1] => equal [2] => different [3] => equal )

php_function_reference.htm

Advertisements