Skip to content
Home » PHP Shorthand If Else (Ternary Operator)

PHP Shorthand If Else (Ternary Operator)

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.

PHP Shorthand If Else (Ternary Operator)
PHP Shorthand If Else (Ternary Operator)

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,

Here are some important examples of PHP shorthand conditions as follows,

Basic True False Declaration

Conditional Startup Message

Conditional Items Message

Conditional Error Reporting Level

Conditional Basepath

Nested PHP Shorthand

Leap Year Check

Conditional PHP Redirect

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:

Was this article helpful?
YesNo

Leave a Reply

Your email address will not be published. Required fields are marked *