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″;