PHP: Using Ternary Operator Condition Checks
Ternary is a short way to write if/else condition checks on a single line, and allows you to perform condition checks inline with variable assignments and more.A ternary condition check takes the form:
CONDITION CHECK ? IF_TRUE : IF_FALSE;
The "?" goes after your condition check, and the ":" separates the true or false branches. The false branch is essentially the "else" of a condition check.
Here is a simple condition check using the ubiquitous if/else structure (one of the many ways to write it out):
if($name == 'Jenkins')
echo 'Hello Jenkins!';
else
echo 'Who are you?';
echo 'Hello Jenkins!';
else
echo 'Who are you?';
The same check can be done with the ternary operator like so:
$name == 'Jenkins' ? echo 'Hello Jenkins!' : echo 'Who are you?';
If concatenating a ternary comparison, put it inside parentheses:
echo 'Hello ' . ($name == 'Jenkins' ? 'Jenkins' : 'Guest') . ', welcome to my site!';
$name = ucfirst(isset($_GET['name']) ? $_GET['name'] : 'Guest');
$name = ucfirst(isset($_GET['name']) ? $_GET['name'] : 'Guest');
