PHP Ternary Operator

Codes can get long, so any kind of shortcut is always welcomed. Enter: The Ternary Operator.

If/Else conditional statements can take up a lot of space. Especially, if you’re like me and like everything to be formatted with plenty of line breaks. Unfortunately, despite being easier to read, all that long winded coding adds to the file size. For example, here is a simple if/else statement:

1
2
3
4
5
 if ($a > $b) {
   echo "A is greater than B";
 } else {
   echo "A is not greater than B";
 }

While alone it doesn’t take up much space, when you have a document that contain dozens of these, the file size can grow fast.

What the Ternary Operator does is take away a bunch of the extra junk that adds to the files size, and gives you a striped down conditional statement.

1
2
3
 $var = (condition) ? true : false;
 // Example
 echo ($a > $b) ? "A is greater than B" : "A is not greater than B";

This can work for any returning functions (return, echo, print, ect), and for any time of variable declaration.

What if I only have a true statement and not a false statement? Then this conditional statement will not work. The Ternary Operator required both and true and false statements. You can use this workaround where if the statement is false, echo nothing:

1
 echo ($a > $b) ? "A is greater than B" : "";

However, if you want a condition with only a true statement, consider the following:

1
 if ($a > $b) echo "A is greater than B";

Notice you need no brackets in this statement. The limitations for this shortcut is that you can only have ONE operation in the true statement. So the following would not work:

1
 if ($a > $b) echo "A is greater than B"; $b++; // returns an error

This function also works for loops:

1
2
3
 while ($var1 = $var2) echo $var1;
 for ($i = 0; $i < count($var); $i++) echo $var[$i];
 foreach ($var as $single) echo $single['name'];

July 1st, 2009 | PHP

Leave a Reply

Name:
Email:
Website:
Message:
SUBMIT