scylla scylla - 2 years ago 63
PHP Question

How do i multiply values of an array

I get this error message "array_product() expects parameter 1 to be array, string given in..." when i try to multiply all the values in the foreach statement below. Kindly help. Thanks in advance

Here is my code. Note that the values in $answer is usually something like "1.50 real(Yes)". but i only need the "1.50" as many as they are in the loop to multiply and get total.

foreach($_POST['gm'] as $key => $answer){
if($answer != ''){
$odd=explode(" ",$answer);
$total = array_product($od);
echo $total;

I try to do the multiplication outside the loop as above with $total. so as not to repeat in the loop. Any help with this please?

Answer Source

You are not reconstructing an array in your foreach loop. So your $od variable does just get overridden each time you loop.

Your code should be

foreach($_POST['gm'] as $key => $answer) {
    if($answer != '') {
        $odd = explode(" ",$answer);
        $od[] = trim($odd[0]);
$total = array_product($od);
echo $total;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download