PHP Shorthand If Else means, when we creates conditional logic code using shortcut operators. There are multiple conditional statements like if else and switch statement, that are used to create conditional flow.
PHP ternary operators are shortcut operators used to convert multiline conditional operator to single line.
Why PHP ternary operator called ternary operator because it takes three operands, one is condition, second is result statement if condition is true and last is result statement if condition is false.

Syntax of Ternary Operator
(Condition) ? (Statement1) : (Statement2);
Condition: Condition is return Boolean value
Statement1: It executed when the condition will return true
Statement1: It executed when the condition will return false
We can also assign the complete condition to the variable like this,
1 |
Variable = (Condition) ? (Statement1) : (Statement2); |
Here are some important examples of PHP shorthand conditions as follows,
Basic True False Declaration
1 |
$is_admin = ($user['permissions'] == 'admin') ? true : false; |
Conditional Startup Message
1 |
echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!'; |
Conditional Items Message
1 |
echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.'; |
Conditional Error Reporting Level
1 |
error_reporting($WEBSITE_IS_LIVE ? 0 : E_STRICT); |
Conditional Basepath
1 |
echo '<base href="http'.($PAGE_IS_SECURE ? 's' : '').'://mydomain.com" />'; |
Nested PHP Shorthand
1 |
echo 'Your score is: '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') ); |
Leap Year Check
1 |
$is_leap_year = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0))); |
Conditional PHP Redirect
1 |
header('Location: '.($valid_login ? '/members/index.php' : 'login.php?errors=1')); exit(); |
Here are the complete list of examples of all comparison shorthand operators. You can also check more on PHP’s official site https://www.php.net/manual/en/language.operators.comparison.php
Let me know if you will face any issues.
Happy coding..!
Also Read:
- PHP: Logout From All Devices on Password Change
- Send Emails in JavaScript Using SMTP with Example
- How to check if an array is empty, NULL, or undefined in jQuery?