繁体   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