@@ -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)
|
||||
|
Reference in New Issue
Block a user