在PHP中使用逻辑运算符if / else

时间:2013-05-01 21:02:54

标签: php if-statement logical-operators

是否可以在PHP的if / then语句的“then”部分使用逻辑运算符?

这是我的代码:

if ($TMPL['duration'] == NULL) {
$TMPL['duration'] = ('120' or '124' or '114' or '138'); }
else {
$TMPL['duration'] = ''.$TMPL['duration']; }

3 个答案:

答案 0 :(得分:3)

使用else if

$a = 1;

if($a === 1) {
    // do something
} else if ($a === 2) {
    // do something else    
}

请注意,在大多数情况下,switch语句更适用于此,例如:

switch($a) {
    case 1:
        // do something
        break;

    case 2:
        // do something else
        break;
}

或:

switch(TRUE) {
    case $a === 1 :
        // do something else    
        break;

    case $b === 2 :
        // do something else
        break;
}

答案 1 :(得分:0)

您的目标是switch吗?

switch($TMPL['duration']) {
    case NULL:
    case '120':
    case '124':
    case '114':
    case '138':
        <do stuff>
        break;
    default:
        $TMPL['duration'] = ''.$TMPL['duration'];
}

答案 2 :(得分:0)

您也可以使用in_array

执行此类操作
if ($TMPL['duration'] === NULL
    || in_array($TMPL['duration'], array('120','124','114','138')) {
    // Do something if duration is NULL or matches any item in the array
} else {
    // Do something if duration is not NULL or does not match any item in array
}