-1

I'm working on a new project and I've come upon the question if the ternary short hand operator the same as using the traditional ternary in combination with the empty() function?

For clarity purposes my question is if: $a ?: $b is the same as !empty($a) ? $a : $b ?

  • Yes, it's just syntactic sugar, the execution is the same. – Barmar Feb 02 '23 at 20:27
  • 3
    If `$a` is not defined with `?:` you'll get a warning. With `!empty` you will not. – u_mulder Feb 02 '23 at 20:29
  • 1
    `$a ?? $b` is more equivalent of the `! empty` – Nigel Ren Feb 02 '23 at 20:35
  • 1
    Why not test it and find out – ADyson Feb 02 '23 at 20:54
  • `?:` works for evaluating "when is set, is empty". What @u_mulder says, the difference is in the warning when it's not set. This fact makes the elvis operator useless in many cases where you might like to use it; use only if you are certain the variable is defined. `??` for "is not set or is null". To "set to value if variable not defined", use `$var ??= 'default';`. (This is equivalent to `!isset($var) && $var = 'default';`.) P.S. You can chain null coalescence, `$var ??= $a ?? $b ?? $c ?? 'sorry';`. – Markus AO Feb 02 '23 at 21:14
  • Relevant reading here: [PHP Elvis operator vs null coalescing operator](https://stackoverflow.com/q/34571330/2943403) and [Check if a variable is empty](https://stackoverflow.com/q/2659837/2943403) and [What does double question mark (??) operator mean in PHP](https://stackoverflow.com/q/53610622/2943403) – mickmackusa Feb 03 '23 at 08:21

1 Answers1

3

$a ?: $b is short-hand for $a ? $a : $b which is not quite the same as !empty($a) ? $a : $b

The difference between them requires careful reading of the definition of the empty pseudo-function:

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false. empty() does not generate a warning if the variable does not exist.

When you just use $a "in boolean context", as in if ( $a ) or $a ? $a : $b or $a ?: $b, its value will be converted to boolean. If the variable doesn't exist - a mistyped variable name, for instance - a Warning will be issued while retrieving that value.

The special power of the empty() pseudo-function is that it won't give you that Warning. The actual result will be the same - an unset variable is considered "equal to false" - but the two pieces of code aren't always interchangeable.

IMSoP
  • 89,526
  • 13
  • 117
  • 169