msgbartop
Adam Palmer MBCS CITP, Linux, PHP Programmer, MySQL Developer, Embedded Hardware, Security Consultant
Did my blog help you? Please link to me!
  dns test
 
RSS Feed
msgbarbottom

15 Jan 09 PHP – Ternary Operator

I’m going to try and focus some time on building out the PHP section of the site now – here’s a useful technique, in shortening and tidying various cases of if/then/else.

This simply operates as:

$result = (condition) ? then : else

Consider the following code:

if (rand(0,1))
{
$result = “A”;
} else {
$result = “B”;
}
echo $result;

We can shorten this using the ternary operator:

$result = (rand(0,1)) ? “A” : “B”;
echo $result;

Or even:

echo (rand(0,1)) ? “A” : “B”;

For more information, see http://uk.php.net/ternary. This is supported in both PHP4 and PHP5

Tags: , ,



Leave a Comment