array _map code example

Example 1: array map

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Example 2: using array map php

array_map ( callable $callback , array $array1 [, array $... ] ) : array

Example 3: 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 4: 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: