The PHP Switch Statement

Switch Statement:

Switch Statement are used to perform different actions based on different conditions. Switch statements are just like if..else conditional statements where a block of code is executed if the condition is true.

Example:

<?php
switch ($x)
{
case 1:
echo “Number 1″;
break;
case 2:
echo “Number 2″;
break;
case 3:
echo “Number 3″;
break;
default:
echo “Hello”;
}
?>

The default case:

What if no number between 1 and 3 are entered? In that case, the default statement in switch code will be executed. In the example above we set the string “Hello”.

The code will executed the default code block since we don’t enter the number between 1 and 3  is not part of our switch statement cases. The code will output “Hello”.

The Break Statement:

The break statement in PHP switch code prevents the code from executing other cases in the switch statement. When a case is matched in a switch statement, the break statement basically stops the code execution. If the break statement is not there, then each case is executed.







Related Posts:

Comments are closed.