简体   繁体   中英

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);
$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

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);

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 .

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,
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM