2 Aug
Are you tired of typing this kind of if statement?
$a = 10;
if ($a > 10)
{
$message = “variable ‘a’ is greater than 10″;
}
else
{
$message = “variable ‘a’ is not greater than 10″;
}
echo $message;
Try this kind instead:
$a = 10;
$message = ($a > 10) ? “variable ‘a’ is greater than 10″ : “variable ‘a’ is not greater than 10″;
echo $message;
The syntax is variable name = condition ? value if true : value if false; I tried to throw some echo statments in place of the values, but PHP doesn’t like that at all. Typing your if statements in this manner could save you a few lines in your code and help to make it easier to read.
I’m sure experienced PHP developers would scoff at this tip, saying “this is so 2001; where have you been?” I still consider myself a rookie at this, so I’d like to help other rookies. Besides, php.net doesn’t explicitly document this syntax (I had to look through the comments to find this).
Edit: On further investigation, I found that I can shorten that even further:
$a = 10;
echo ($a > 10) ? “variable ‘a’ is greater than 10″ : “variable ‘a’ is not greater than 10″;
3 Responses for "Alternative If Statement Syntax In PHP"
The ternary operator is generally considered *less* easy to read.
You don’t have the visual cue of indentation and, once the operation gets complex enough, you need to go back to the old form anyway.
IMHO, this is the preferred form:
$a = 10;
if ($a > 10) {
echo “variable ‘a’ is greater than 10″;
} else {
echo “variable ‘a’ is not greater than 10″;
}
There are a few developers who disagree, like the guys who made WordPress. Everytime I ran into that syntax, it confused the hell out of me. So now I know how to read it, and I’m inclined to agree with your view (although I would put each curly brace on its own line).
It could be easier to read in some very specific circumstances, like this (assume we are trying to change the color of odd-numbered rows in a table):
<tr id=”<? if ($i % 2 == 0) { echo “even”; } else { echo “odd”; } ?>”><td>…</td></tr>
<tr id=”<? echo ($i % 2 == 0) ? “even” : “odd”; ?>”> …</td></tr>
That saves what, 14 characters? Looking at the above, I’m not so sure I really demonstrated anything useful.
Hmmm… I see Will’s inner nerd is try to bust out. FIGHT IT WILL!!!! If I see you with a pocket protector, I will subject you to a nerd-exorcism. Don’t force me to take this course of action. :p lol
Leave a reply