msgbartop
I will happily conduct a FREE basic web security scan for any genuine organization interested in my services to point out whether or not I can find vulnerabilities in your application. Just contact me.
Need a PHP Programmer, PHP staff or project manager? Contact me now.
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

You must be logged in to post a comment.