且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Switch 语句返回错误结果

更新时间:2022-06-19 08:21:32

您想要的行为可以通过 if else 或三元运算符来实现(这几乎只是一种快捷方式编写if/else).这是一个未经测试的粗略示例.

The behavior you want would be achieved with an if else, or the ternary operator (which is pretty much just a short hand way of writing an if/else). Here's a rough untested example.

function airport($one, $two, $three) {
   if ( !empty($one) || !empty($two) || !empty($three) ) {
         $one = !empty($one) ? "Airline Name: $one<br>" :"Airline Name: PLEASE PROVIDE AIRLINE NAME<br>";
         $two = !empty($two) ? "Flight Number: $two<br>" : "Flight Number: PLEASE PROVIDE FLIGHT NUMBER<br>";
         $three = !empty($three) ? "Departure Airport: $three<br>" : "Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT<br>";
   }
   echo $one, $two, $three;
}
airport($airline_name,$flight_number,$departure_airport);

至于为什么您的 switch 没有按照您的预期执行,根据手册:

As to why your switch doesn't perform as you expect, per the manual:

只有当 case 语句的值与 switch 表达式的值匹配时,PHP 才会开始执行这些语句.PHP 会继续执行语句,直到 switch 块结束,或者第一次看到 break 语句. 如果没有在 case 语句列表的末尾编写 break 语句,PHP将继续执行以下案例的语句.

Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

-http://php.net/manual/en/control-structures.switch.php