简体   繁体   中英

PHP if statements with multiple values

Is there a shorter way of writing this?

<? 
if($_GET['id']==1 ||
$_GET['id']==3 ||
$_GET['id']==4 || 
$_GET['id']==5)
{echo 'does it really have to be this explicit?'};
?>

Something like this perhaps?

<?
if($_GET['id']==1 || 3 || 4 || 5){echo 'this is much shorter'};
?>

只需尝试:

if ( in_array($_GET['id'], array(1, 3, 4, 5)) ) {}

Maybe not shorter but more readable. Try the in_array() function:

if (in_array($_GET['id'], array(1, 3, 4, 5)))
{
  echo "What about this?";
}

Perhaps switch may help

switch($_GET['id']) {
    case 1: 
    case 3: 
    case 4: 
    case 5:
        echo 'Slect maybe :P';
        break;
}

您可以使用如下正则表达式:

preg_match(['1-4']);

Declare an array:

$values = array(1,3,4,5);

Get your variable

$id = $_GET['id'];

Now use PHP in_array();

if(in_array($id, $values)){
//do something
}

Read about in_array()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM