'Multiply each value in array using array_map function

I'm trying to multiply each value from array_module_rate array.

The result should be:

  • $array_module_rate[0] = 25
  • $array_module_rate[1] = 15
  • $array_module_rate[2] = 20

How I can do it?

$array_module_rate = array(
  '5',
  '3',
  '4'
}

$global_course = 5;

array_map(function($cal) {
  return $cal * $global_course;
}, $array_module_rate);


Solution 1:[1]

$array_module_rate = array(
  '5',
  '3',
  '4'
}

$global_course = 5;

foreach($array_module_rate as $key=>$value){
   $array_module_rate[$key]=$global_course* $value;
}

You can use a foreach loop

Solution 2:[2]

Use closure to send additional argument in array_map callback.

$array_module_rate = array(
  '5',
  '3',
  '4'
);

$global_course = 5;

array_map(function($cal) use($global_course) {
  return $cal * $global_course;
}, $array_module_rate);

Solution 3:[3]

If you want to modify the original array, you can use array_walk instead of array_map. It takes the array by reference, so if you pass the array element to the callback by reference as well, you can modify it directly.

array_walk($array_module_rate, function(&$cal) use ($global_course) {
   $cal *= $global_course;
});

Note that you need to pass $global_course into the callback with use, otherwise it won't be available in that scope.

Solution 4:[4]

Modern PHP has "arrow functions" which allow you to access global scoped variables within an anonymous function body. This allows you to concisely multiply each element by the $global_course factor using a clean, functional approach.

Code: (Demo)

var_export(
    array_map(fn($v) => $v * $global_course, $array_module_rate)
);

Output:

array (
  0 => 25,
  1 => 15,
  2 => 20,
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anandhu
Solution 2 zen
Solution 3 Don't Panic
Solution 4 mickmackusa