How to code if/else
statements
An if
clause with one statement and no braces (Not Recommended)
if (!isset($rate)) $rate = 0.075; // Jim... Not recommended
An if
clause with one statement and braces (Recommended)
if ($qualified) { // This expression is equivalent to $qualified == true.
echo("You qualify for enrollment.");
}
if
and else
clauses with one statement each and no braces (Not Recommended)
if ($age >= 18)
echo("You may vote.");
else
echo("You may not vote.");
Why you should always use braces with else
clauses
if ($age >= 18)
echo("You may vote.");
else
echo("You may not vote.");
$may_vote = false; // This statement isn't a part of the else clause.
Braces make your code easier to modify or enhance
if ($score >= 680) {
} else {
}
hp if (1=1) {
}
A nested if statement to determine if a year is a leap year
$is_leap_year = false;
if ($year % 4 == 0) {
if ($year % 100 == 0) {
if ($year % 400 == 0) {
$is_leap_year = true; // divisible by 4, 100, and 400
} else
$is_leap_year = false; // divisible by 4 and 100 but not 400
}
} else {
$is_leap_year = true; // divisible by 4, but not 100
}
} else {
$is_leap_year = false; // not divisible by 4
}
- If you only have one statement after an if statement or an else clause, you don’t have to put braces around that statement.
Jim... I do not recommend not using braces. At some future oint yu may need to add a statement and you may forget to add the braces at that time and will get wrong results.
- You can nest an if statement within the if, else if, or else clause of another if statement. This nesting can continue many layers deep.
Back