Php – Ternary Operators
We have previously examined the
if-elseif-else conditional statements. We know that these statements provides branching ability according to the conditions. While using this statements in single and simple situations it may become trivial task. Php provides an alternative way for a simple usage. This is called ternary operators.
Syntax of ternary operator is like below. Php looks to the CONDITION and if the result is
true the TRUE part is executed if not FALSE part code is executed.
(CONDITION ? TRUE : FALSE)
Here we will check the login function status and if the login is successful the function will return
true part of the ternary operator will be executed.
$status = login();
($status ? echo "Successfully logged on" : echo "Login Failed");
- Ternary operator will make code simpler
- Ternary operator will make code more readable
- Ternary operator will make code shorter