This question already has an answer here:
Not sure why I'm getting this error as the code is working and I can see the data I expected.
Code
$allSales = array();
foreach ($game['sales'] as $sale) {
foreach ($sale['values'] as $id => $values) {
$allSales[$id]+=$values['y'];
}
}
Error 1
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: player/game.php
Line Number: 81
Error 2 (Same Code)
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: player/game.php
Line Number: 81
</div>
The statement:
$allSales[$id] += $values['y'];
means to take the current value of $allSales[$id]
, add the value of $values['y']
to it, and store that result back in $allSales[$id]
. But the first time that you encounter a particular $id
, there is no $allSales[$id]
. This results in the warning when you try to get its current value.
Change to:
if (isset($allSales[$id])) {
$allSales[$id] += $values['y'];
} else {
$allSales[$id] = $values['y'];
}
Or you could just prefix the line with @
to suppress warnings (I know purists will cry over this):
@$allSales[$id] += $values['y'];