Guide to PHP and MySQL (University at Buffalo Version)


Chapter 4: Using Conditionals

PHP conditionals provide a way to execute a statements or statements based on whether some condtion is met or not met.

PHP if/else Conditional

The if statement allows you to test whether some condition is true or false. If the result of the test is true then the statement(s) between the first { and } are executed. If the result is false the then statement(s) between the else { and } are executed. For example:

<?php
$mood = "happy";
if ($mood == "happy") {
  print("We are in a good mood");
} else {
  print("We are not happy :-(");
}
?>

Figure 4-1: PHP if/else Statements
We are in a good mood

Figure 4-2: PHP if/else Output

PHP switch Conditional

The switch statement allows you to test whether some condition is met or not met. If the parzmeter that is passed to the switch statement is equal to any of the case statements then the statement(s) between that case: statement and break statement are executed. If the parameter does not match any of the case statements then the statements after the default: statement(s) are executed. For example:

<?php
$favTeam = "yankees";
switch ($favTeam) {
  case "red sox":
    echo("Your favorite team is the Boston Red Sox.");
    break;
  case "yankees":
    echo("Your favorite team is the New York Yankees.");
    break;
  case "blue jays":
    echo("Your favorite team is the Toronto Blue Jays.");
    break;
  default:
    echo("Your favorite team is not the yankees or the red sox or the blue jays.");
}
?>

Figure 4-3: PHP switch Statement Using a String
Your favorite team is the New York Yankees.

Figure 4-4: PHP switch Using a String Output
<?php
$secretNumber = 3;
switch ($secretNumber) {
  case 1:
    echo("Your secret number is 1.");
    break;
  case 2:
    echo("Your secret number is 2.");
    break;
  case 3:
    echo("Your secret number is 3.");
    break;
  default:
    echo("Your secret number is not 1 or 2 or 3.");
}
?>

Figure 4-5: PHP switch Statement Using a Number
Your secret number is 3.

Figure 4-6: PHP switch Statement Using a Number Output
Let's Get Started with a PHP if/else Page!
Let's Get Started with a PHP switch Page!
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2018 Jim Gerland