chrisstump
3/16/18 at 11:30 am
PHP
PHP: Ternary Operators
Using ternary operators offer a quick and clean way to build inline if / else statements in PHP.
// in this example, we are checking to see if the user is logged in // if the user is logged in, we will output the user's first name (e.g., 'Hello Chris') // if the user is not logged in, we will output 'Hello Guest' // the value to the left of the ':' is the true condition and the value to the right is the else condition echo 'Hello '.($user->isLoggedIn() ? $user->firstName : 'Guest'); // written the long way, this would look like this: if($user->isLoggedIn()) { echo 'Hello '.$user->firstName; } else { echo 'Hello Guest'; }
Copy Snippet to Clipboard
Don't Have an Account?
Stop digging through old code examples. Get organized. Get Code Snipper.
Learn More
Start Free 14 Day Trial