Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multiply each value in the array by an additional argument [duplicate]

Tags:

html

css

php

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!


1 Answers

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

like image 119
Hanky Panky Avatar answered Feb 20 '26 12:02

Hanky Panky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!