The Shorthand ternary operator in PHP is a much more compressed and essentially one line equivalent to the traditional tabbed if-else comparison that can easily span several lines.
The ever common if-else conditional statement looks like this:
if ($var) { echo 'Yes'; } else { echo 'No'; }
If $var
is true then yes will be displayed.
With ternary the statement layout is as follows:
condition ? true : false;
Instead of using five or more lines the comparison is done on just one! The outcome is separated by : with the true outcome being before and false outcome after it.
Here is that first example but in a ternary style:
echo ($var) ? 'Yes' : 'No';
It does exactly the same thing, just saves space.
Another example and a more common usage type being:
echo 'Welcome ' . (isset($_SESSION['uid']) && !empty($_SESSION['uid']) ? $_SESSION['username'] : 'guest') . '';
If the session is set and not empty then “Welcome username” will be outputted else it will say “Welcome guest”.
This is shorter than writing it out traditionally however I don’t see it as easier to read, likely due to them not being used a lot personally.
Going through recent code I can find plenty of times when ternary could have been used like:
public function validateEmail(): bool { if (filter_var($this->email, FILTER_VALIDATE_EMAIL) && strlen($this->email) <= 60) { return true;//Valid email address } else { return false; } }
Turned into:
public function validateEmail(): bool { return (filter_var($this->email, FILTER_VALIDATE_EMAIL) && strlen($this->email) <= 60) ? true : false; }
Its use comes down to personal preference.