Having an array of the type:
$arr = array(23,4,13,50,231,532,3);
$factor = 0.4;
I need to produce a new array where all values of $arr
are multiplied/divided by $factor
. I'm aware of foreach
method. Just thought, there must be a more elegant approach.
PHP 5.3 and higher:
$arr = array(23,4,13,50,231,532,3);
$arr_mod = array_map( function($val) { return $val * 0.4; }, $arr);
To pass in the factor dynamically, 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 accepts should match the number of arrays passed to the
array_map()
.
It does not make too much sense in this simple example, but it enables you to define the callback independently somewhere else, without any hard-coded values.
The callback will receive the corresponding values from each array you pass to array_map()
as arguments, so it's even thinkable to apply a different factor to every value in $arr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With