Home > PHP Functions, PHP Switch, Shafiq Ahmed > PHP Switch Statement

PHP Switch Statement

switch/case is very similar or an alternative to the if/elseif/else commands. The switch command will test a condition. The outcome of that test will decide which case to execute. Switch is normally used when you are finding an exact (equal) result instead of a greater or less than result.
switch (condition) {casevalue1” :
block of coding;
if the condition equals value1;
break;

casevalue2” :
block of coding;
if the condition equals value2;
break;

default :
block of coding;
if the condition does not equal value1 or value2;
break;

}
?>

There can be many cases listed. For example purposes, we only show two. There are a few things happening at the same time here :

1. The switch condition is examined and a value is found.
2. The condition value is passed through the cases.
3. If the value matches a case value, the code in that block is executed.
4. If the value does not match any of the case values, the default section is executed.
5. Once a block of coding is finished, the BREAK command is used to jump out of the switch/case area.

$test = 32;switch ($test) {

case “40″ :
echo “The value equals 40.”;
break;

case “32″ :
echo “The value equals 32.”;
break;

default :
echo “The value is not 40 or 32.”;
break;

}
?>

And the result :

The value equals 32.
Categories: PHP Functions, PHP Switch, Shafiq Ahmed Tags:
  1. No comments yet.
  1. No trackbacks yet.