PHP: One-Armed Conditional Statements II

Derek Bridge

Department of Computer Science,
University College Cork

PHP: One-Armed Conditional Statements II

Aims:

Class exercise

Common errors I

if $age < 18 
{
    echo 'You are too young to study CS1109';
    echo 'Come back when you\'re older.';
}

Common errors II

if ( $age < 18 );
{
    echo 'You are too young to study CS1109';
    echo 'Come back when you\'re older.';
}

Common errors III

if ( $age < 18 ) 
    echo 'You are too young to study CS1109. ';
    echo 'Come back when you\'re older.';

Common errors IV (probable error)

if ( $age < 18 )
{ 
    echo 'You are too young to study CS1109. ';
    echo 'Come back when you\'re older.';
}
if ( $age > 18 )
{
    echo 'Welcome to CS1109.';
}

Common errors V

if ( $age = 18 ) 
{
    echo 'You are the perfect age to study CS1109.';
}

Explaining common error V, part I: assignment

Explaining common error V, part I: assignment

Explaining common error V, part II: Boolean values

The following all convert to false The following all convert to true
0
0.0
'' (empty string)
'0'
An array with zero elements
An object with no values or functions
NULL
All other values

Explaining common error V, part II: Boolean values

Can we now explain common error V?

if ( $age = 18 ) 
{
    echo 'You are the perfect age to study CS1109.';
}

HTML for radio buttons

Guess my favourite colour
<form action="colour.php" method="get">
   <fieldset>
      <legend>Guess my favourite colour</legend>
      <div>
         <input type="radio" name="colour" value="red" id="red" checked="checked" />
         <label for="red">Red</label>
         <input type="radio" name="colour" value="green" id="green" />
         <label for="green">Green</label>
         <input type="radio" name="colour" value="blue" id="blue" />
         <label for="blue">Blue</label>
      </div>
   </fieldset>
    
   ...submit button, etc...
    
</form>

HTML for radio buttons

PHP for radio buttons

$colour = $_GET['colour'];

$winnings = 0;
if ( $colour == 'green' )
{
    $winnings = 5;
}
echo "<p>You win {$winnings} eurines!</p>";