3

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

Modify this function so that you can pass an additional argument to this function. The function should multiply each value in the array by this additional argument (call this additional argument 'factor' inside the function). For example 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 so far:

$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? Thanks!

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95

4 Answers4

5

Your function is not right, It has to return that 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

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • If you wrap the ```array_map``` in another function, like I've done in my answer, you have the benefit of having all logic once, even when the function is re-used. That makes it easier to add sanity checks (like what to do with non-numeric input) in the multiplication closure. – Arjan Jul 02 '15 at 05:54
  • Yep that makes sense. Nice answer. – Hanky Panky Jul 02 '15 at 05:56
  • It goes through your array elements one by one and then multiplies them by your number and stores all the new values in a new array and then at the end it returns that new array to the caller and then your code stores that as `$B` – Hanky Panky Jul 02 '15 at 06:09
  • Great! Very straightforward. –  Jul 02 '15 at 06:13
2

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

function multiply($array, $factor) {
    return array_map(function ($x) {return $x * $factor}, $array);
}
Arjan
  • 9,784
  • 1
  • 31
  • 41
0
$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);
Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48
0
$myArray = [2, 3, 5];
$factor = 3;

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

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

or like this if no $factor variable requared

array_walk($myArray, function(&$v) {$v *= 3;});
Sergey Onishchenko
  • 6,943
  • 4
  • 44
  • 51