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:
$mood = "happy";
if ($mood == "happy") {
print("We are in a good mood");
} else {
print("We are not happy :-(");
}
?>
if/else
Statementsif/else
OutputPHP 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:
$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.");
}
?>
switch
Statement Using a Stringswitch
Using a String Output$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.");
}
?>
switch
Statement Using a Numberswitch
Statement Using a Number Output