PHP multiply each value in an array by an optional argument

I was trying to create a PHP function that multiplies the values ​​/ contents of an array by a given argument.

Modify this function so you can pass an additional argument to this function. The function should multiply each value in the array by this extra argument (let's call this extra argument the "factor" inside the function). For example, let's say $ A = array (2,4,10,16). When you say

$B = multiply($A, 5);  
var_dump($B);
this should dump B which contains [10, 20, 50, 80 ]

      

Here's my code:

$A = array(2, 4, 10, 16);

        function multiply($array, $factor){
            foreach ($array as $key => $value) {
                   echo $value = $value * $factor;
            }

        }

        $B = multiply($A, 6);
        var_dump($B);

      

Any idea? Thank!

+3


source to share


4 answers


Your function is wrong, it should return this array and not echo some values.

    function multiply($array, $factor)
    {
        foreach ($array as $key => $value)
        {
                  $array[$key]=$value*$factor;
        }
        return $array;
    }

      

Rest is fine.

Fiddle



You can even do this with array_map

$A = array(2, 4, 10, 16);
print_r(array_map(function($number){return $number * 6;}, $A));

      

Fiddle

+5


source


A simpler solution where you don't have to iterate over the array yourself, but instead use the native php functions (and closures):



function multiply($array, $factor) {
    return array_map(function ($x) {return $x * $factor}, $array);
}

      

+2


source


$A = array(2, 4, 10, 16);

function multiply($array, $factor){
    foreach ($array as $key => $value) {
        $val[]=$value*$factor;
    }
    return $val;
}

$B = multiply($A, 6);
var_dump($B);

      

0


source


$myArray = [2, 3, 5];
$factor = 3;

array_walk($myArray, function(&$v) use($factor) {$v *= $factor;});

// $myArray = [6, 9, 15];

      

or like this, if the $ factor variable is not specified

array_walk($myArray, function(&$v) {$v *= 3;});

      

0


source







All Articles