简体   繁体   中英

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

Say I have an array that looks like this:

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

How can I dynamically check to see if the area has any empty values?

You can use empty() :

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

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

See the type comparison table for more information.

Something like

// $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);

For this you have more possibility:

  1. You can use array_filter function without without a second parameter

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

but for this be carful because this remove all values which are equal false (null, false, 0)

  1. You can use array_filter function with callback function:

     function filterEmptyValue( $value ) { return ! empty( $value ); } array_filter([ 'empty' => null, 'test' => 'test'], 'filterEmptyValue'); 
  2. You can use foreach or for:

     $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]); } } 

    This is samples so you must think and make good solution for your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM