2013-03-27 112 views
1

這是世界上最簡單的php if語句創建,我怎麼永遠無法弄清楚如何做到這一點,在一個。基本上我有一個難倒的時刻,並要求社區的幫助。無法弄清楚如何創建這個if語句

這是我的函數:

protected function _traverse_options($name, $type = ''){ 

    if(isset($this->_options[$name][$type])){ 
     echo $this->_options[$name][$type]; 
    } 
} 

if語句我需要的是檢查三兩件事:

  • 如果類型不爲空類型不是 '前'
  • 如果類型不爲空類型不是'後'

我試着這樣做:

if($type != '' && $type != 'before' || $type != '' && $type != 'after'){} 

如何以往任何時候都不起作用。

我知道這很簡單,但我無法弄清楚它?應該||&& ??

+0

'&&'的優先級高於'||'嗎? – Izkata 2013-03-27 20:54:53

+1

此外,即使'null ==''',您應該使用'$ type === null'(或'!==') - 它更準確,更不可能導致奇怪的錯誤。例如,如果'$ type'確實是''''出於某種原因?或者[其他與「'''相同的內容](http://www.php.net/manual/en/types.comparisons.php)? – Izkata 2013-03-27 20:57:18

回答

0

這將做的工作。 嘗試:

if (!is_null($type) && strlen($type) > 0 && $type !== 'before' && $type !== 'after') { ... } 
0

因此,任何非空字符串既不是before也不是after。如果我的理解是正確的,你不需要或者該聲明

if($type != '' && $type != 'before' && $type != 'after'){} 
0

if ('' !== $type && !in_array($type, array('before', 'after'))) 
{ 

} 
0

使用括號,以便您可以看到什麼屬於什麼。

if ($type != null && ($type !== 'before' && $type !== 'after')) { 
    // ... 
} 

如果你不小心,你可能有問題的,比如數學,其中計算可以給出兩種不同的結果取決於何種操作,你先做結束。例如2*5-10,它可以是0-10,具體取決於您乘以或減去的順序:(2*5)-102*(5-10)

你也可以把它變得更輕鬆打破了邏輯到變量,使得跟隨if語句簡單:

$notNull = ($type != null); 
$notBeforeAndAfter = ($type !== 'before' && $type !== 'after'); 
if ($notNull && $notBeforeAndAfter) { 
    // ... 
} 

如果你確切地知道該$type變量必須包含,那麼你也可以使用一個switch聲明。這很容易理解:

switch ($type) { 
    case 'before': 
     echo '$type is "before"'; 
     break; 
    case 'after': 
     echo '$type is "after"'; 
     break; 
    // $type is not 'before' or 'after', which means that 
    // it is something else which we cannot use... 
    default: 
     echo '$type is an unknown value. Error maybe?'; 
     break; 
}