Latest web development tutorials

PHP Switch Statement

switch statement is used to perform different actions based on a number of different conditions.


PHP Switch Statement

If you want to selectively execute one of several blocks of code, use the switch statement.

grammar

switch (n)
{
case label1:
	如果 n=label1,此处代码将执行;
	break;
case label2:
	如果 n=label2,此处代码将执行;
	break;
default:
	如果 n 既不等于 label1 也不等于 label2,此处代码将执行;
}

How it works: First, a simple expressionn (usuallyvariable) once calculated. The value and structure of the expression in each case were compared. If there is a match, the case associated code is executed. After the code is executed, using thebreak to prevent the code jump to the next case to continue execution.Executive default statement is used to match does not exist (that is, no case is true) time.

Examples

<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
    echo "你喜欢的颜色是红色!";
    break;
case "blue":
    echo "你喜欢的颜色是蓝色!";
    break;
case "green":
    echo "你喜欢的颜色是绿色!";
    break;
default:
    echo "你喜欢的颜色不是 红, 蓝, 或绿色!";
}
?>

Running instance »