Created
February 22, 2020 00:35
-
-
Save DominicWatts/8f666fbc2095700c501668ba625475d5 to your computer and use it in GitHub Desktop.
PHP : Ternary Operators (?:) #php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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