From 91e036523af166506956327e76567aa860e6c744 Mon Sep 17 00:00:00 2001 From: Hassan <43174720+hassanrafi39@users.noreply.github.com> Date: Fri, 29 Mar 2019 05:27:58 +0600 Subject: [PATCH] Ternary Operators (#31060) php ternary operators. --- guide/english/php/operators/index.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/guide/english/php/operators/index.md b/guide/english/php/operators/index.md index 23d37e48d2..184a162262 100644 --- a/guide/english/php/operators/index.md +++ b/guide/english/php/operators/index.md @@ -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)