Most worthy way to multiply / split array values ​​by $ var in PHP

The presence of an array of type:

$arr = array(23,4,13,50,231,532,3); $factor = 0.4; 

I need to create a new array where all the values ​​of $arr are multiplied / divided by $factor . I know the foreach method. Just thought there should be a more elegant approach.

+4
source share
4 answers

PHP 5.3 and later:

 $arr = array(23,4,13,50,231,532,3); $arr_mod = array_map( function($val) { return $val * 0.4; }, $arr); 

To dynamically transmit a dynamic coefficient, do:

 $arr_mod = array_map( function($val, $factor) { return $val * $factor; }, $arr, array_fill(0, count($arr), 0.4) ); 

as the docs say:

The number of parameters that the callback function takes must match the number of arrays passed to array_map() .

In this simple example, this does not make much sense, but allows you to define a callback independently from each other, without any hard-coded values.

The callback will receive the corresponding values ​​from each array that you pass into array_map() as arguments, so you can even use different values ​​for each value in $arr .

+11
source

You can use array_map to apply a callback function (which does the multiplication) to each element of the array:

 function multiply($n) { $factor = 0.4; return($n * $factor); } $arr = array_map("multiply", $arr); 

Perfect link

+5
source

Note that after 5.3 pre 5.3 you could use array_map as suggested (maybe my first choice) or array_walk, and pass ref

 array_walk($arr, create_function('&$val', '$val = $val * 0.4;')); 
+2
source

To dynamically convey dynamic and compressed syntax, you can use the following in later versions of PHP (> 5.3.0, I think):

 $arr = array(23,4,13,50,231,532,3); $factor = 0.5; $arr_mod = array_map( function($val) use ($factor) { return $val * $factor; }, $arr ); 
0
source

All Articles