map php array code example

Example 1: php map array

function cube($number)
{
    return ($number * $number * $number);
}

$nums = [1, 2, 3, 4, 5];
$cubed = array_map('cube', $nums);

Example 2: array map php

The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.

Tip: You can assign one array to the function, or as many as you like.

Syntax
array_map(functionname, array1, array2, array3, ...)
  
Example
Send each value of an array to a function, multiply each value by itself, and return an array with the new values:

<?php
function myfunction($val)
{
  return($val*$val);
}

$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>

Example 3: php array map

$func = function cube($n) {
    return ($n * $n * $n);
}
$a = [1, 2, 3, 4, 5];
$b = array_map( $func, $a );

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

Tags:

Php Example