.net 3d art blog c# coding college computers editorial entertainment firefox food freeware gaming hardware hdtp hiking humor ide japan japan, javascript linux mac mailbox milestone misc. mods momoiwa, mono movie nintendo philosophy php politics rant rebun review science software technology test time ucr wakkanai windows work wormholeftp 日本
Ternary conditional operators are incredibly useful in PHP (and just about every other programming language) because they turn a multi-line IF statement into a single line! Case in point:
if($variable == "hello")
{
$response = true;
}
else
{
$response = false;
}
Becomes:
$variable == "hello" ? $response = true : $response = false;
And just like that, I've saved 7 lines of code! This is incredibly helpful when you need to check multiple variables and don't want to write up an entire if...else... statement to assign values to other variables.
And now that I've blogged about this structure, I won't have to look all over the internet when I need it but have forgotten what it's called.
Although EER's first snippet is the cleanest way, you usually would use the ternary operator like this:
$response = $variable == "hello" ? true : false;
By EER @ Wed Feb 20, 2008 04:10 PM
OR ... $response = ($variable === "hello");
OR ...
if($variable == "hello")
$response = true;
else
$response = false;
Lots of ways to save lines ;)