How to multiply or add php values?

Asked

Viewed 1,461 times

0

I have an array with values and a variable that will inform whether to multiply or sum the values of this array, to make the sum user o array_sum, now has some function to multiply?

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

$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;
    }        
}
  • The answer was to what he was looking for?

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: http://ideone.com/i6aA9R

Browser other questions tagged

You are not signed in. Login or sign up in order to post.