2012-09-18 53 views
2

在此question and answer之後,我決定接受來自其他開發人員/用戶的輸入的布爾真和假,並且而不是甚至nullPHP is_null:只有布爾值true和false,甚至不是null?

$default = array(
    "category_id" => null, 
    "category"  => false, 
    "randomise"  => false 
); 

$config = array(
    "category_id" => 17, 
    "randomise"  => false, 
    "category"  => null 
); 

function process_array($default,$config) 
{ 
    # Set empty arrays for error & items. 
    $error = array(); 
    $items = array(); 

    # Loop the array. 
    foreach($default as $key => $value) 
    { 
     if (is_bool($default[$key]) && isset($config[$key])) 
     { 
      if ($config[$key] === null) $error[] = '"'. $key.'" cannot be null.'; 

      # Make sure that the value of the key is a boolean. 
      if (!is_bool($config[$key])) 
      { 
       $error[] = '"'. $key.'" can be boolean only.'; 
      } 

     } 

      if(isset($config[$key]) && !is_array($value)) 
      { 
       $items[$key] = $config[$key]; 
      } 
      elseif(isset($config[$key]) && is_array($value)) 
      { 
       $items[$key] = array_merge($default[$key], $config[$key]); 
      } 
      else 
      { 
       $items[$key] = $value; 
      } 
     } 

     # Give a key to the error array. 
     $error = array("error" => $error); 

     # Merge the processed array with error array. 
     # Return the result. 
     return array_merge($items,$error); 
} 

print_r(process_array($default,$config)); 

但結果我得到的是,

Array 
(
    [category_id] => 17 
    [category] => 
    [randomise] => 
    [error] => Array 
     (
     ) 

) 

結果我之後,

Array 
(
    [category_id] => 17 
    [category] => 
    [randomise] => 
    [error] => Array 
     (
     [0] => "category" cannot be null. 
     ) 

) 

所以我想,低於此線應該工作,但我不明白爲什麼它沒有。我試圖使用is_null,但仍然無法正常工作。任何想法我做錯了什麼,我該如何解決這個問題?

if ($config[$key] === null) $error[] = '"'. $key.'" cannot be null.'; 

回答

3

我相信null值將無法通過isset()試驗if (is_bool($default[$key]) && isset($config[$key])),所以它跳過了整個街區。

你需要重構一下來解決這個問題。也許如果將它置於空測試中,那麼可以採用isset?

if (!isset($config[$key]) || is_null($config[$key])) $error[] = '"'. $key.'" cannot be null.';

+0

不錯,趕上!猜你是對的 –

+0

謝謝散貨,我把喬迪的答案完美的作品!謝謝! – laukok

1

null不會通過is_bool檢查或者......據我所知 - 當談到if statements - 最好是儘可能簡單:

if (is_null($default[$key])) 
{ 
    $error[] = '"'. $key.'" cannot be null.'; 
} 
else if (!is_bool($default[$key])) 
{ 
    $error[] = '"'. $key.'" can be boolean only.'; 
} 

至於另一個海報指出的那樣,它也最好將上述內容包裝在array_key_exists中以避免非法偏移警告。 Tbh,爲了簡單起見,你是否真的需要這些檢查?指定key只能是布爾值應該足夠。

+0

謝謝你的解釋,pebbl。 – laukok

相關問題