0

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 ?

13
  • 1
    Side note: How do you have a function name that starts with ~? Commented Sep 3, 2015 at 18:23
  • 1
    @phpisuber01: Not part of the name php.net/manual/en/language.operators.bitwise.php Commented Sep 3, 2015 at 18:25
  • ~r (REF) is a library for dumping stuff Commented Sep 3, 2015 at 18:27
  • 2
    How is your catch catching this? It's a notice not an exception/error. Commented Sep 3, 2015 at 18:42
  • 1
    @RocketHazmat Maybe he's defined a custom error handler, as in stackoverflow.com/questions/5373780/… Commented Sep 3, 2015 at 18:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.