Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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.

like image 714
Z. Zlatev Avatar asked Nov 29 '10 14:11

Z. Zlatev


1 Answers

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.

like image 194
Tomalak Avatar answered Nov 02 '22 12:11

Tomalak