How to multiply or add php values?

0

I have an array with values and a variable that will tell you whether to do a multiplication or sum of the values of that array, to make the user sum array_sum , now have some function to multiply?

I did this, but I would like to know if you have problems the way I did and / or if you have better way to do this:

$arr = array(2.00, 4.10, 5.00, 1.21);

echo calcValues($arr, "+"); // 12.31
echo calcValues($arr, "*"); // 49.61

function calcValues($values, $operacao)
{   
    if($operacao == "+")
    {
        return array_sum($values);
    }
    else
    {
        $res = 1;
        foreach ($values as $v) {
            $res *= $v;
        }
        return $res;
    }        
}
    
asked by anonymous 01.12.2014 / 18:12

1 answer

8

There is a function for this, array_product .

Test like this:

function calcValues($values, $operacao){   
    if ($operacao == "+"){
        return array_sum($values);
    }
    elseif ($operacao == "*"){
        return array_product($values);
    }
}

The result is:

echo calcValues($arr, "+"); // 12.31
echo calcValues($arr, "*"); // 49.61

Example: link

    
01.12.2014 / 18:15