6

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'};
?>
4

5 回答 5

30

只需尝试:

if ( in_array($_GET['id'], array(1, 3, 4, 5)) ) {}
于 2013-10-02T14:30:09.773 回答
4

也许不是更短但更具可读性。试试 in_array() 函数:

if (in_array($_GET['id'], array(1, 3, 4, 5)))
{
  echo "What about this?";
}
于 2013-10-02T14:35:44.287 回答
2

也许 switch 可能会有所帮助

switch($_GET['id']) {
    case 1: 
    case 3: 
    case 4: 
    case 5:
        echo 'Slect maybe :P';
        break;
}
于 2013-10-02T14:33:33.807 回答
1

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

preg_match(['1-4']);
于 2013-10-02T14:36:43.523 回答
0

声明一个数组:

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

获取你的变量

$id = $_GET['id'];

现在使用 PHP in_array();

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

阅读in_array()

于 2013-10-02T14:34:35.380 回答