Core PHP, PHP Beginners

PHP Shorthand If Else (Ternary Operator)

Written by Bikash · 1 min read >

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
Written by Bikash
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP. Profile

Leave a Reply

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