开发者

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

开发者 https://www.devze.com 2023-01-27 05:22 出处:网络
Having an array of the type: $arr = array(23,4,13,开发者_如何学编程50,231,532,3); $factor = 0.4;

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.


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

function multiply($n) {
        $factor = 0.4;
        return($n * $factor);
}

$arr = array_map("multiply", $arr);

Ideone link


Note there are true lambadas after 5.3 pre 5.3 you could use array_map as suggested (probably my first choice) or array_walk and pass by ref

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


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

精彩评论

暂无评论...
验证码 换一张
取 消