Search code examples
phpoperatorselvis-operator

PHP: Please help explain these ternary operators


Can anyone explain this operator please? I realise its now deprecated in 7.4 so refactoring.

This example:

if ($this->interestAreas()->count() > 0) {
    $ids ?: $ids = $this->interestAreas()->pluck('id');
    $this->interestAreas()->detach();
}

I understand it when ?: is used assigning a variable eg: $newUser = ($user) :? null; but not as above. Can anyone explain how that may be rewritten?


Solution

  • Imagine ? and : as conditional variables, a string like

    $a = 1 ? $b : $c;
    

    can be read like:

    If $a equals 1 then show $b, if not show $c;