Ternary Operators (#31060)

php ternary operators.
This commit is contained in:
Hassan
2019-03-29 05:27:58 +06:00
committed by Randell Dawson
parent ea700759fe
commit 91e036523a

View File

@@ -24,3 +24,26 @@ echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
```
### Ternary Operators
If you need a very short, simple, easy maintaining that work just like if else statement then php give you ternary operator. A very poweful but easy operator. It looks like this - (?:). Simple, right? Lets get to examle.
Suppose you need to send a massage that if the user is logged in then say 'Hello user_name' if not then 'Hello guest'.
if we use if-else statement:
```
if($user == !NULL {
$message = 'Hello '. $user;
} else {
$message = 'Hello guest';
}
```
Using ternary operator:
```
$message = 'Hello '.($user == !NULL ? $user : 'Guest');
```
Both of them do exactly same thing. But the later one is easy for maintainance.
#### More Resources
- [PHP Shorthand If/Else Using Ternary Operators (?:)](https://davidwalsh.name/php-shorthand-if-else-ternary-operators)