2013-05-01 125 views
-5

是否有可能在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

回答

3

使用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

0

你瞄準一個switch

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