Tech-Evangelist

Technical Articles, Musings and Opinions from Tech-Evangelist

  • Home
  • About
  • Guidelines
Previous article: Preventing SQL Injection with MySQL and PHP
Next article: Troubleshooting Mozilla Thunderbird Incoming E-Mail Problems

How to Use the PHP Ternary Operator

November 11, 2007 By Jonathan - Copyright - All Rights Reserved

The ternary operator is a shortcut comparison operator that replaces an if-else statement in a PHP script. If you use a lot of comparison statements in your scripts, this can greatly reduce the number of lines of code. The ternary operator is really very simple to use, but it does tend to confuse newbie PHP programmers.

The ternary operator is only used for assignment of values to variables and to reduce the lines of code and compact PHP statements. Although it is a little more difficult to read, once you understand how it operates, it is simple to use and understand.

There are four parts to a ternary statement. The first is the variable where the result of the conditional test will be assigned. The second part is he condition that is being evaluated for a True or False boolean result. The third part is the value that is assigned if the condition is true. The last part is the value assigned if the condition is false.

$variable = condition ? if true : if false

Let’s start with the most common use of this shortcut. If your scripts are processing large amounts of data that users have entered using HTML forms, you are undoubtedly assigning the form values to variables. When a value does not exist, a default value would normally be assigned like this:

 if (isset($_POST['statusID']))
{
  $statusID = $_POST['statusID'];
}
else 
{
  $statusID = 1;
}

Using a ternary operator statement, that same conditional test and assignment of values would look like this:

$statusID =  (isset($_POST['statusID'])) ? $_POST['statusID'] : 1;

The interpretation is: If a value has been passed in the form variable named statusID via the POST method, assign that value to $statusID. If no value was passed, assign the default value of 1.

Sometimes you will see a variation of the same statement that looks like this:

$statusID = (empty($_POST['statusID'])) ? 1 : $_POST['statusID'];

The result will be the same, but the condition being tested has been flipped–rather than testing to see if a value does exist, it is testing to see if a value is missing. The interpretation is: If a no value has been passed via the POST method, assign the default value of 1. If a value was passed, assign that value to $statusID.

Ternary operators really shine when assigning text to simple messages, such as:

$msg = ($age < 21) ? 'Minor - no drinks' : 'Adult - have a beer';
echo $msg;

The interpretation is: If the value in $age is less than 21, then “Minor, no drinks” is assigned to $msg, else “Adult – have a beer” is assigned.

Here is a cool method for assigning alternating background colors to table rows or other tabular displays of data.

<?php
$names = array("John Doe","Susan Doe","Snuffy Smith","Jack Jones");
$c = count($names);

echo "<table width='300' style='border:1px solid #c7c7c7'>\n";

for($i=0; $i<$c; $i++)
{ 
 $bg = ($i % 2 == 0) ? '#d7d7d7' : '#ffffff'; 
 echo "<tr height='10' bgcolor='$bg'><td> $names[$i] </td></tr>\n"; 
} 

echo "</table>\n"; 
?> 

Running this code will display the following:

ternary operator example

While this example uses an array, it is just as simple to do the same using data extracted from MySQL.

Filed Under: PHP Tutorials, Web Site Development

Comments

  1. Adam says

    November 12, 2007 at 5:11 pm

    I personally can’t wait for the introduction of PHP6’s optional adaptation of the ternary operator. Instead of doing like:

    $myVar = $_GET[‘myVar’] ? $_GET[‘myVar’] : ‘Not set’;

    You will be able to do:

    $myVar = $_GET[‘myVar’] ?: ‘Not set’;

    How handy will that be!

  2. Doogie says

    November 13, 2007 at 5:52 am

    There are a lot of nice features in PHP 5 and the upcoming PHP 6. Unfortunately, most hosting companies have still not upgraded from PHP 4. 🙁

  3. Joyel says

    March 28, 2009 at 12:47 pm

    They may not currently be migrating but a lot of them are going from 4 to 5. If the PHP community would get in contact with there hosts and start talking to them about upgrading they will (create demand and they will respond).

  4. Inzei says

    November 24, 2009 at 6:38 am

    @Adam: IIRC that’ll still result in E_NOTICE when trying to get a value with nonexistent key, and thus such markup should be avoided.

Categories

  • Affiliate Marketing
  • CSS Tutorials
  • FileZilla Tutorials
  • Home Theater
  • Internet Marketing
  • Internet Technology
  • Kindle Tips
  • MySQL Tutorials
  • Online Auction Tips
  • Paint Shop Pro Tutorials
  • PHP Tutorials
  • Tech News
  • Thunderbird Tutorials
  • Video Production
  • Web Site Development
  • WordPress Tutorials
follow me on Twitter
Content and images are copyrighted by Tech-Evangelist.com and others

Copyright © 2022 Tech-Evangelist.com - All Rights Reserved
Posted code samples are free to use. Do not reproduce or republish articles or content on another web site.

Privacy Policy : Terms of Use