Skip to content
Advertisement

How to explode a string and calculate a sum?

I want $total to be output as just a sum of a number but everytime i sum up $total it outputs multiple numbers

$total =0   // i tried to use a number to sum them up
$computers = array(
"computer;DT-12;568,36;10",
 "Samsung; RS; 562,26;11",
 "Hewlett Packard;  F12; 450,23; 23",
"Toshiba; LO-34; 454,23;8",
 "Sony; Vaio 123; 232,23;5"
);
foreach($computers   as $value)
{
$product= explode(";",$value);

    $price = $product[2];

         $count = $product[3];
           $multiply = $count * $price;
$total += $multiply

}

expected output:

$total =  27004 as one number

Advertisement

Answer

There were a few syntax errors in your codes. Other than that, your calculation looks fine, and great job with explode();.

Code:

$computers = array(
    "computer;DT-12;568,36;10",
    "Samsung; RS; 562,26;11",
    "Hewlett Packard;  F12; 450,23; 23",
    "Toshiba; LO-34; 454,23;8",
    "Sony; Vaio 123; 232,23;5",
);

$total = 0;
foreach ($computers as $value) {
    $product = explode(";", $value);
    $total += (int) trim($product[2]) * (int) trim($product[3]);
}

var_dump($total);

Output:

You might check out to see if the math is right.

int(27004)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement