H3XED

PHP: Using Ternary Operator Condition Checks

Apr 5, 2012   Programming   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
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?';

The same check can be done with the ternary operator like so:

echo $name == 'Jenkins' ? 'Hello Jenkins!' : 'Who are you?';
If concatenating a ternary comparison, put it inside parentheses:

echo 'Hello ' . ($name == 'Jenkins' ? 'Jenkins' : 'Guest') . ', welcome to my site!';

$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter