PHP: Nested Conditionals
Derek Bridge
Department of Computer Science,
University College Cork
PHP: Nested Conditionals
Aims:
- to learn about nested
if-else
statements
- to practice reasoning about supposedly equivalent programs
- to learn how to avoid the dangling-
else
problem
A program with nested-if
s
$status = $_GET['status'];
$sex = $_GET['sex'];
$salary = (int) $_GET['salary'];
$threshold = 0;
$tax_rate = 0.0;
$tax = 0.0;
if ( $status == 'single' )
{
if ( $sex == 'F' )
{
$threshold = 20000;
$tax_rate = 0.3;
}
else // i.e. $sex == 'M'
{
$threshold = 18000;
$tax_rate = 0.4;
}
}
else // i.e. $status == 'married'
{
$threshold = 32000;
$tax_rate = 0.25;
}
if ( $salary > $threshold )
{
$tax = $tax_rate * ($salary - $threshold);
}
echo "<p>Send us {$tax} eurines or your first-born child</p>";
Class exercise
- Rewrite the
if-else
to eliminate the nested-if
- Compare the two versions
The dangling-else
problem
- Confusion can arise when a statement mixes a
one-armed conditional with a two-armed conditional
- There will be two
if
s and one
else
- So which
if
does the else
belong to?
- PHP is uninfluenced by your indentation
- PHP has a simple rule:
The else
belongs to the most recent
if
, unless braces dictate otherwise
- Class exercise: Rewrite the program using
new indentation to show how the
else
actually related to the if
s
Avoiding the dangling-else
problem
Avoiding the dangling-else
problem
if ( B1 )
{
if ( B2 )
{
S1;
}
else
{
S2;
}
}
|
if ( B1 )
{
if ( B2 )
{
S1;
}
}
else
{
S2;
}
|