PHP

PHP Menu

PHP

Switch...Case - PHP Basics

The switch statement is used to select one of many blocks of code to be executed. This is an alternative to the if...elseif...else statement.

The syntax for the switch...case statement is as follows:

<?php
switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; }
{ "error_message":"You need to input values for this code to run." }

The break keyword prevents the code from running into the next case automatically. The default keyword is used if no match is found.

Below is an example of the switch...case statement. Try changing the value of $bmonth.

<?php
$bmonth = "October";
switch ($bmonth) { case "January": echo "You are born in January!"; break; case "February": echo "You are born in February!"; break; case "March": echo "You are born in March!"; break; case "April": echo "You are born in April!"; break; case "May": echo "You are born in May!"; break; case "June": echo "You are born in June!"; break; case "July": echo "You are born in July!"; break; case "August": echo "You are born in August!"; break; case "September": echo "You are born in September!"; break; case "October": echo "You are born in October!"; break; case "November": echo "You are born in November!"; break; case "December": echo "You are born in December!"; break; default: echo "You are probably an alien!"; }

Exercise

Create a variable named grade. Write a script that displays Excellent if grade is "A", Average when the value of grade is "B" and Poor when the value is "C". Use the switch-case statement. Test your code by assigning the value "A" to $grade.

<?php
$var = 123
<?php
$grade = "A"; switch($grade) { case "A": echo "Excellent"; break; case "B": echo "Average"; break; case "C": echo "Poor"; break; default: echo "No assigned value to variable."; }
{ "test_output_contains":{ "expected":"Excellent", "error_message":"Did you assign the correct value for <code>$grade<\/code>?" }, "test_variable_exists":{ "object":"$grade", "error_message":"Have you declared <code>$grade<\/code>?" }, "success_message":"Good job!", "error_message":"Please read the instructions again." }

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods