Skip to content

Most decent way to multiply/divide array values by $var in PHP

An answer to this question on Stack Overflow.

Question

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.

Answer

To pass the factor dynamically and with a concise syntax you can use the following in more recent (>5.3.0, I think) versions of PHP:

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