In my php applicaiton I have the following code:
try {
$ordersIngredients[$userIngredient->getId()][$day] += $quantity;
} catch (\Exception $e) {
~r(array(
$ordersIngredients[$userIngredient->getId()],
$day,
array_key_exists($day, $ordersIngredients[$userIngredient->getId()]),
$e->getMessage()
));
}
The r() function prints the following:
array(4)
0 => array(4)
0 => 0.9
1 => null
2 => null
3 => 1
)
1 => 3
2 => true
3 => Notice: Undefined offset: 3
)
How can I have an error on un undefined offset when the offset actually exists given the dump of the array and array_key_exists ?
1 Answer 1
The issue here is that you were trying to append to a value that did not exist in the array.
$ordersIngredients[$userIngredient->getId()][$day] += $quantity;
This is the same as writing:
$ordersIngredients[$userIngredient->getId()][$day] =
$ordersIngredients[$userIngredient->getId()][$day] + $quantity;
So, what's happening is that PHP is trying to read the value at index 3, but it can't. That's what causes your notice. Since it's only a notice, PHP treats the undefined index as null and keeps going. It then adds null + $quantity to your array.
After finishing the line, it moves into your error handler and then to your catch block.
~?catchcatching this? It's anoticenot an exception/error.