簡體   English   中英

檢查數組是否具有不帶值的鍵,然后執行此操作(PHP)?

[英]Check if an array has a key without a value, then do this (PHP)?

說我有一個看起來像這樣的數組:

Array
(
    [0] => 
    [1] => 2017-01-01 00:00:00
)

如何動態檢查該區域是否有空值?

您可以使用empty()

$array = [
  null, 
  '2017-01-01 00:00:00',
  '',
  [],
  # etc..
];

foreach($array as $key => $value){
  if(empty($value)){
    echo "$key is empty";
  }
}

有關更多信息,請參見類型比較表

就像是

// $array = [ ... ];

$count = count($array);

for( $i=0; $i<=$count; $i++){
    if( $array[$count] == 0 ){
         // Do something
    }
}

通過將數組值與array_filter的結果(刪除空值)進行比較,可以查看它是否具有空值。

$has_empty_values = $array != array_filter($array);

為此,您更有可能:

  1. 您可以在沒有第二個參數的情況下使用array_filter函數

    array_filter([ 'empty' => null, 'test' => 'test']);

但是對此要小心,因為這會刪除所有等於false(null,false,0)的值

  1. 您可以將array_filter函數與回調函數一起使用:

     function filterEmptyValue( $value ) { return ! empty( $value ); } array_filter([ 'empty' => null, 'test' => 'test'], 'filterEmptyValue'); 
  2. 您可以將foreach或用於:

     $array = ['empty' => null, 'test' => 'test']; foreach($array as $key => $value) { if(empty($value)) { unset($array[$key]); } } $array = [null, 'test']; for($i = 0; $i < count($array); $i++){ if(empty($array[$i])) { unset($array[$i]); } } 

    這是示例,因此您必須思考並為您的問題提供良好的解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM