How to use the PHP ternary operator ?

How to use the PHP ternary operator ?

People are already familiar with all type of PHP’s statement like if statement. It is too much similar to other counterparts in different other programming languages. This statement also represents the fundamental concepts of programming. They If the statement is so easy statement to understand and also easy to execute.
PHP:
<?php
if ($Factor >= 10) {
$message = "You are one cool dude!";
}
else {
$message = "Sorry, you aren't that cool!";
}
But there is also a another way to increase your $Factor. You can do this with ternary operator. Ternary operator is also use to, serves the shorthand for if statements.

Ternary Operator:

Ternary operator is made with their Consisting. In ternary operator we separate the expressions with colon and question mark. Mostly people think that question mark is use as test expression and colon is use to separates two possible value. First value question mark is use as true and second value colon which is use as false.
PHP:
<?php
$message=($Factor>=10)?"You're one cool dude!":"Sorry, you aren't that cool!";
One more use of ternary operator is its use to check that value which is set or not and if it’s not set then set a default value for variable.
PHP:
<?php
$favColor=isset($_GET["color"])?$_GET["color"]:"white";
If a parameter color is passed from script given in URL whose value is assigned to variable $ favColor and if it’s not then the default value is “white”

If the test value will come “true” then it’s a Boolean context, then its value will be true. Otherwise, alternative value is returned as it was.
PHP:
<?php
$favColor=$_GET["color"]?:"white";
When we use ternary operator properly then the result will come in cleaner code and if you use ternary operator as abusing it will make thinks messy. So never sacrifice the maintainability and readability of your code.

Don’t Ever Abuse ternary operator:

If you are using ternary operator then always be ready for the complexity of using this. if you are using any kind of stacking or nesting operations then always avoid them rather how much comfortable they are. Always use if statements in complex situations. Always make your code easy to understand and clean.

Don’t ever separate ternary expressions into multiple lines. There are various different ways to use white-space liberally. Its’ always use to improve readability of code.
PHP:
<?php
$message=$isWinner
?"Congratulations! You just won a whole bunch of money and prizes!"
:"Sorry, you didn't get any money or prizes this time.";
Author
bhawanisingh
Views
2,144
First release
Last update
Rating
0.00 star(s) 0 ratings
Top