English 中文(简体)
Can I use a logical "or" in a PHP switch statement case?
原标题:

Is it possible to use "or" or "and" in a switch case? Here s what I m after:

case 4 || 5:
    echo "Hilo";
    break;
最佳回答

No, but you can do this:

case 4:
case 5:
       echo "Hilo";
       break;

See the PHP manual.

EDIT: About the AND case: switch only checks one variable, so this won t work, in this case you can do this:

switch ($a) {
  case 4:
    if ($b == 5) {
      echo "Hilo";
    }
    break;
  // Other cases here
}
问题回答

The way you achieve this effectively is :

CASE 4 :
CASE 5 :           
    echo "Hilo";           
    break;

It s called a switch statement with fall through. From Wikipedia :

"In C and similarly-constructed languages, the lack of break keywords to cause fall through of program execution from one block to the next is used extensively. For example, if n=2, the fourth case statement will produce a match to the control variable. The next line outputs "n is an even number.". Execution continues through the next 3 case statements and to the next line, which outputs "n is a prime number.". The break line after this causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message."

No, I believe that will evaluate as (4 || 5) which is always true, but you could say:

case 4:
case 5:
    // do something
    break;

you could just stack the cases:

switch($something) {
   case 4:
   case 5:
       //do something
       break;
}
switch($a) {
    case 4 || 5:
        echo  working ;
        break;
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签