Php 我可以有多个案例做同样的事情吗?
第一种方法确实有效,但下面哪一种是有效的方法Php 我可以有多个案例做同样的事情吗?,php,switch-statement,Php,Switch Statement,第一种方法确实有效,但下面哪一种是有效的方法 switch($type) { case 1: print 'success'; break; case 2: print 'success'; break; case 3: print 'success'; break; case 4: print 'success for type 4'; break; } 既然
switch($type) {
case 1:
print 'success';
break;
case 2:
print 'success';
break;
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
既然1、2和3打印都是一样的,我可以这样做吗
switch($type) {
case 1, 2, 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
或
这就是路 PHP手册列出了一个类似于您的第三个示例:
我同意其他人对以下内容的使用:
switch ($i) {
case 0: //drop
case 1: //drop
case 2: //drop
echo "i is 0, 1, or 2";
break;
// or you can line them up like this.
case 3: case 4: case 5:
echo "i is 3, 4 or 5";
break;
}
我唯一要添加的是多行下拉式case语句的注释,这样当您(或其他人)在最初编写代码后查看代码时,您就知道它不是bug
switch($type)
{
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>
switch ($i) {
case 0: //drop
case 1: //drop
case 2: //drop
echo "i is 0, 1, or 2";
break;
// or you can line them up like this.
case 3: case 4: case 5:
echo "i is 3, 4 or 5";
break;
}