PHP array map

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP: array_map() function

PHP: Applies the callback to the elements of the given arrays

The array_map() function sends each value of an array to a user defined function and gets an array with new values applied by the user defined function.

Version

(PHP 4 and above)

Syntax

array_map(user-supplied-function, array1, array2, ...)

Parameters

Name

Description

Required /
Optional

Type

user_function

The user defined function to run for each element in each array.

Required

Array

array1

Specifies an array to run through the user defined function

Required

Array

array2....

Specifies an array to run through the user defined function

Optional

Array

Return value

An array containing all the elements of array1 after applying the user_function() to each one.

Value Type : Array

Pictorial Presentation :

php array array_map()

Example :

  1. function square($x)  

  2. {  

  3. return($x * $x);  

  4. }  

  5. $a = array(10,12,14,16,18,20);  

  6. $b = array_map("square",$a);  

  7. print_r($b);  

  8. ?>  

Output :

Array ( [0] => 100 [1] => 144 [2] => 196 [3] => 256 [4] => 324 [5] => 400 )