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

问题描述:

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

这是我的代码:

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

什么是你'then'语句逻辑意义?我不明白你想要实现什么...... – Xaltar 2013-05-01 21:03:55

+0

使用管道标志? '|' – arminb 2013-05-01 21:04:09

+0

我认为他的意思是'elseif'? – Pankrates 2013-05-01 21:04:12

使用else if

$a = 1; 

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

注意,在大多数情况下,开关语句是更好,如:

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; 
} 
+0

我想要做的是如果持续时间等于NULL,通过随机选择一个来设置持续时间等于任何这些数字。那可能吗? – Roku 2013-05-01 21:25:27

+0

使用这个:http://pastebin.com/6sNhh83G – hek2mgl 2013-05-01 21:29:39

你瞄准一个switch

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

你也可以做这样的事情利用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 
}