[英]Check if an array has a key without a value, then do this (PHP)?
說我有一個看起來像這樣的數組:
Array
(
[0] =>
[1] => 2017-01-01 00:00:00
)
如何動態檢查該區域是否有空值?
就像是
// $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);
為此,您更有可能:
您可以在沒有第二個參數的情況下使用array_filter
函數
array_filter([ 'empty' => null, 'test' => 'test']);
但是對此要小心,因為這會刪除所有等於false(null,false,0)的值
您可以將array_filter
函數與回調函數一起使用:
function filterEmptyValue( $value ) { return ! empty( $value ); } array_filter([ 'empty' => null, 'test' => 'test'], 'filterEmptyValue');
您可以將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.