Creating a new array with PHP array_map()

To create a new array from an existing PHP array, you can use the array_map($callback, $array1, $array2, ...) function. The array_map() function iterates over all the elements of an array and returns a new array containing the results of applying the given $callback function to the array elements. The array_map() function does not change the original array but creates a new one. You can pass several arrays to the array_map() function. The number of parameters the $callback function takes must match the number of arrays passed to the array_map(). The first parameter is the name of a user-defined callback function applied to all array elements. The second parameter specifies the array to process. In this PHP Array Map example, we use the array_map() function to loop over an array and return a new array, where a callback function has been applied to each element in the array. Click Execute to run the PHP Array Map Example online and see the result.
Creating a new array with PHP array_map() Execute
<?php
function func($v)
{
  return($v * 2);
}

$array = array(1, 2, 3, 4, 5);

print_r(array_map("func",$array));
?>
Updated: Viewed: 2084 times

How to use the array_map function in PHP?

Following is the syntax of the array_map() function:

PHP array_map() Syntax
array_map(functionName, array1, array2, array3 ...)

Where:
  • functionName: the required parameter that defines the name of the user-defined callback function applied to all elements of the array
  • array1: the required parameter that specifies the array to process
  • array2, array3 (optional): additional arrays to pass to the callback function
PHP Map Array Example
<?php
function func($v)
{
  return($v * 2);
}

$array = array(5, 4, 2, 2, 3);

print_r(array_map("func",$array));
?>

#output: Array
(
    [0] => 10
    [1] => 8
    [2] => 4
    [3] => 4
    [4] => 6
)

See also