PHP: Nested Conditionals

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Nested Conditionals

Aims:

Example

A program with nested-ifs

$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

Class exercise

The dangling-else problem

Avoiding the dangling-else problem

Avoiding the dangling-else problem

if ( B1 )
{
    if ( B2 )
    {
        S1;
    }
    else
    {
        S2;
    }
}
if ( B1 )
{
    if ( B2 )
    {
        S1;
    }
}
else
{
    S2;
}

Class exercise