0

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);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Konrad Strek
  • 71
  • 1
  • 9
  • You're not doing anything with the result of `array_map()`. It doesn't modify the array in place, it returns a new array. – Barmar Aug 22 '18 at 22:40

4 Answers4

0
$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

Anandhu
  • 807
  • 1
  • 9
  • 22
0

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);
zen
  • 980
  • 6
  • 18
0

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.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

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,
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136