If Else in PHP Using Ternary Operators (?:)

Previously we have discussed how to write if else in PHP using brackets or colon: If Else, and Elseif in PHP, in addition, there is another way to do it that is using ternary operators (? 🙂 or in another word: shorthand if else.

I. The Writing Rule of Ternary Operators (?:)

You have to write ternary operators like the following form:

$var = expression1 ? expression2 : expression3

if expression1 evaluated to TRUE, then the resulting value is expression2, otherwise, if the expression1 is FALSE, then the resulting value is expression3. The value of expression1, expression2 and expression2 can be anything, including a function.

If written in a common format (using brackets), the code looks like this:

if ( expression ) { 
	$var = expression2 
} else { 
	$var = expression3 
}

an example of using ternary operators (simple):

$value = 7;
echo $value > 7 ? 'Good' : 'Average'; // Average

If written using brackets, then it would be like this:

$value = 7;
if ($value > 7) {
	echo 'Good';
} else {
	echo 'Average';
}

II. Another Way of Writing Ternary Operators

Since PHP 5.3, you can eliminate the expression2, so the rule becomes like this:

$var = expression1 ?: expression3

which means if expression1 evaluated to TRUE,  then the resulting value is expression1, otherwise, the resulting value is expression3. If written in a general form, it becomes:

if ( expression1 )
{
	$var = expression1;
} else {
	$var = expression3;
}

For example:

$value = '';
echo $value ?: 7; // 7

III. Combining With String

If you combine ternary operators with a string, you have to use parentheses, so that PHP will parse it as a statement rather than a string, otherwise, it will cause an error. For example:

//ERROR: Parse error: parse error, unexpected ':' 
$select .='<option value="1" '. $status == "1" ? 'selected="selected"' :''.'>Yes</option>';

//Work
$select .='<option value="1" '.($status == "1" ? 'selected="selected"' :'').'>Yes</option>';

IV. Nested If Else

Ternary operators can be written with any level of depth (not limited) – “if else inside if else”  (nested if else) -, while the writing rule is:

expression1 ? expression2 : (expression3 ? expression4 : (etc..))

An example:

$value = 6;
$predicate = $value > 8 ? 'Excellent' : ( $value >= 7 && $value <= 8 ? 'Good' : ($value <= 6 && $value > 5 ? 'Average' : 'Bad') );
echo $predicate; // Average

More shorten:

$value = 6;
echo $value > 8 ? 'Excellent' : ( $value >= 7 && $value <= 8 ? 'Good' : ($value <= 6 && $value > 5 ? 'Average' : 'Bad') );

The above code is confusing, right? and more difficult to maintain, because there are a lot of if else in a single line of code, so ideally -in my opinion- two is the most, otherwise, it would be better using the common format (using brackets).

BUT if you want to keep using this, make sure to make the code easy to read and understandable, so change the above code to the following:

$value = 7
$predicate = $value > 8
			? 'Excellent' 
			: ( $value >= 7 && $value <= 8 
				? 'Good' 
				: ( $value <= 7 && $value > 5 
					? 'Average' 
					: 'Poor'
				   ) 
			  );
echo $predicate; // Average

Changed into brackets-style:

if ( $value > 8 ) {
	$predicate = 'Sangat Baik';
} else if ( $value >= 7 && $value <= 8 ) {
	$predicate = 'Baik';
} else if ( $value <= 6 && $value > 5 ) {
	$predicate = 'Sedang';
} else {
	$predicate = 'Kurang';
}

IV. Advantages of Using Ternary Operators (? 🙂

Here is some benefit of writing if else in PHP using ternary operators:

  1. Writing if else becomes faster and shorter because you don’t need to write the keywords if and else
  2. Code becomes easier to read, especially for inline code (one line of code) and more easily when combining with strings, etc.
  3. Maintenance of code becomes easier.

V. Some Tips for Using Ternary Operators (?:)

Here are some useful tips for using ternary operator:

  1. As in the previous example, if you write multiple if else in one statement (nested if else), if it possible, break your code into multiple lines, it will improve the readability and more easy to maintenance.
  2. If necessary, use parentheses, it will keep your code organized, but don’t be bloated.
  3. If you still confuse using ternary operators, first, write the code in the common form (using brackets) and then translate it into ternary operator form.

VI. Some Example of Using Ternary Operators (?:)

Some example of using ternary operators (?:)

<?='Welcome ' . ($this->isLogIn ? $this->_name : 'Guest, Please Login')?>
// Another Style
<?='Welcome ' . ($this->_nama ?: 'Guest, Please Login')?>

More complex:

$value = array(1 => 9, 7, 8, 9, 7, 10, 7, 9, 8, 8, 9, 8);	
for ($i = 1; $i <= 12; $i++)
{
	$months[$i] = date("F", mktime(0, 0, 0, $i+1, 0, 0));
}		
foreach ($months as $num => $month)
{
	// Ternary Operators
	$quarter = $num >= 1 && $num <= 3 
				? 1 
				: ($num >= 4 && $num <= 6
					? 2
					: ($num >= 7 && $num <= 9 ? 3 : 4)
				  );
				
	$semester = $num >= 1 && $num <= 6 ? 1 : 2;
			
	$result['quarter'][$quarter][$month] = $value[$num];
	$result['semester'][$semester][$month] = $value[$num];
}

/* Result:
Array
(
    [quarter] => Array
        (
            [1] => Array
                (
                    [January] => 9
                    [February] => 7
                    [March] => 8
                )
            [2] => Array
                (
                    [April] => 9
                    [May] => 7
                    [June] => 10
                )
            [3] => Array
                (
                    [July] => 7
                    [August] => 9
                    [September] => 8
                )
            [4] => Array
                (
                    [October] => 8
                    [November] => 9
                    [December] => 8
                )
        )

    [semester] => Array
        (
            [1] => Array
                (
                    [January] => 9
                    [February] => 7
                    [March] => 8
                    [April] => 9
                    [May] => 7
                    [June] => 10
                )
            [2] => Array
                (
                    [July] => 7
                    [August] => 9
                    [September] => 8
                    [October] => 8
                    [November] => 9
                    [December] => 8
                )
        )
) */

Subscibe Now

Loves articles on webdevzoom.com? join our newsletter to get quality article right to your inbox. Nothing else, just quality stuff!!!

Related Post

Leave a comment

Like Us

Newsletter

Great information from webdevzoom.com right to your inbox

We value your privacy

Social