1

I want to use the null coalesce operator like this

$response['shares']->getField('count') ?? 0

What this should do is to get the share count or if its not set get 0. The problem I'm having now is, that sometimes the array index shares does not exist so I'm getting ErrorException: Undefined index: shares. I know that I could do it like this

isset($response['shares']) ? $response['shares']->getField('count') : 0 but is there a way to do that with the null coalesce operator directly without checking every index for its existence?

Musterknabe
  • 5,763
  • 14
  • 61
  • 117
  • 2
    No. Since first you can't call a method on something which doesn't exists. So if you try to check if it exists first with `$response['shares'] ?? ...` then it would return that if it exists and you won't be able to call the method. – Rizier123 Apr 22 '16 at 09:46
  • So I would need to go the old way here? – Musterknabe Apr 22 '16 at 09:51
  • 2
    You can't call a method on a non existent index, so yes you have. – Rizier123 Apr 22 '16 at 09:53

0 Answers0