romalong
10-15-2003, 11:55 AM
Just begun to learn PHP.
I never did C before, though to underswtand bsics i need to dig into it step by step.
Just wonder how to correct this snippet:
if ($age>20) {
echo "You are older than 20 years old.";
} else
{
echo "You are younger than 20 years old.";
}
I mean if I enter 20 in form, script outputs: You are younger than 20 years old. Why does it behave such way? I need it to say: You are 20. How to make it?
TNX!
It behaves like that because 20 = 20 and your condition 20 > 20 will return false.
So you could do something like
if ($age == 20) {
echo "You are 20 years old.";
} elseif ($age> 20) {
echo "You are older than 20 years old.";
} elseif ($age < 20) {
echo "You are younger than 20 years old.";
}
Or you could use a switch() http://be2.php.net/manual/en/control-structures.switch.php
missing-score
10-15-2003, 04:21 PM
or, if you wanted to do a single line:
$return = ($age > 20) ? "You are older than 20" : ($age == 20) ? "You are 20" : "You are younger than 20";
echo $return;
this does basically what was put above, but in a single line.
Spookster
10-15-2003, 07:21 PM
Originally posted by missing-score
or, if you wanted to do a single line:
$return = ($age > 20) ? "You are older than 20" : ($age == 20) ? "You are 20" : "You are younger than 20";
echo $return;
this does basically what was put above, but in a single line.
The technical name for doing so is using the ternary operator. The ternary operator being the ? character.
Simply put, a shortcut way of writing a conditional if/else block. It's use is typically discouraged though due to poor readability and in some people's cases writability.
missing-score
10-15-2003, 09:43 PM
thanks.. never knew it was called that. :)
romalong
10-16-2003, 12:11 PM
oh...thank all of you, lads!