Skip to content

Instantly share code, notes, and snippets.

@DominicWatts
Created February 22, 2020 00:35
Show Gist options
  • Save DominicWatts/8f666fbc2095700c501668ba625475d5 to your computer and use it in GitHub Desktop.
Save DominicWatts/8f666fbc2095700c501668ba625475d5 to your computer and use it in GitHub Desktop.
PHP : Ternary Operators (?:) #php
## most basic usage
$var > 2 ? true : false
## another basic usage
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
## shorthand usage
$message = 'Hello '.($user->get('first_name') ?: 'Guest');
## echo, inline
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');
## result will be the value of $initial, unless $initial evaluates to false, in which case the string 'default'
$result = $initial ?: 'default';
## Same as writing this
$result = $condition ? $condition : 'default';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment