Control Flow: Switch 3/6
Switch Syntax
A
switch
statement is similar to an if
/ elif
/ else
statement in that you can check multiple conditions. Here's what it looks like:$myNum = 2;
switch ($myNum) {
case 1:
echo "1";
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
default:
echo "None of the above";
}
- A
switch
statement is made up of theswitch
keyword, a variable to check, and a pair of curly braces{ }
. Here we check the value of$myNum
. - Then we have a
case
block for each comparison. For examplecase 1: echo "1";break;
checks whether $myNum is equal to 1. If yes, itecho
s "1", and usesbreak
to exit theswitch
statement. - Otherwise, the next
case
block runs. - If all
case
s return false, thedefault
case gets executed.
Instructions
On line 10, there's a
switch
statement- Fill the
__
spots with the correct code. Check out the example above - Add the
default
case.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$fruit = "Apple";
switch ($fruit) {
case "Apple":
echo "Yummy.";
break;
default:
echo "Yummy";
}
?>
</body>
</html>
Comments
Post a Comment