Search code examples
phpassociative-arrayconditional-operator

Why is this shorthand ternary operator throwing an error?


I have this code in a method:

$remainder_payment = $this->product_info['remainder_payment'] ?: 0;

And I am getting this error:

Undefined index: remainder_payment in...

In my mind I am setting $remainder_payment to $this->product_info['remainder_payment'] if $this->product_info['remainder_payment'] is not false, otherwise $remainder_payment = 0.

Looking at this table in the manual if an item in undefined then it should evaluate to false, but instead I'm getting an error.


Solution

  • You're right that the ternary operator is essentially an if statement, and like an if statement it will throw the warning if you try to access the array key without it existing.

    What you want is the null coalescing operator ??

    $remainder_payment = $this->product_info['remainder_payment'] ?? 0;