Assignment 1

Barry Molina

Conditions

Conditons are how logic is expressed in PHP. They make use of logical operators to create expressions whose computed value determines whether or not a section of code is run.

The simplest condition is a single if statement:

$should_run_code = true;

if ($should_run_code) {
  echo 'Code is running.';
}

Output:

Code is running.

if statements can optionally include elseif and else clauses:

$running_time = 8;

if ($running_time > 12) {
  echo 'You must be new.';
} elseif ($running_time > 9) {
  echo 'You\'re relatively in shape.';
} elseif ($running_time > 5) {
  echo 'I\'m impressed!';
} elseif ($running_time > 4) {
  echo 'You must be an elite marathon runner.';
} else {
  echo 'You\'re joking';
}

Output:

I'm impressed!

Sometimes, many elseif clauses can be expressed more succinctly using the switch statement:

$door_choice = 3;

switch ($door_choice) {
  case 1:
    echo 'Wrong door.';
    break;
  case 2:
    echo 'Wrong door.';
    break;
  case 3:
    echo 'You found the goat!';
    break;
}

Output:

You found the goat!
conditions.php source code screenshot
conditions.php source code screenshot