-1

I am using foreach over an array and adding each member and assigning total to a variable.

It works like i want, but I get the error:

Notice: Undefined variable: total in C:\xampp\htdocs\preg.php on line 10

I dont quite understand how/why this works and why I get the ^^ error

<?php
    $bar = [1,2,3,5,36];
    foreach($bar as $value) {
        $total = ($total += $value);        
    }

    echo $total;
?>
Stereo99
  • 234
  • 1
  • 9

1 Answers1

0

Before the foreach you need

$total = 0;
foreach($bar as $value){....

The $total variable wasn't initialised, so it couldn't be added to itself. Also, you can rewrite the whole thing like this:

$bar = [1,2,3,4,5];
$total = 0;
foreach($var as $value) {
    $total += $value;
}
echo $total;
Jonno_FTW
  • 8,601
  • 7
  • 58
  • 90