user4671351
user4671351

Reputation:

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?

Upvotes: 0

Views: 3128

Answers (4)

Przemek Dziadek
Przemek Dziadek

Reputation: 51

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

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

You can see if it has any empty values by comparing the array values to the result of array_filter (which removes empty values.)

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

Upvotes: 1

Ben Lonsdale
Ben Lonsdale

Reputation: 725

Something like

// $array = [ ... ];

$count = count($array);

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

Upvotes: 0

Xorifelse
Xorifelse

Reputation: 7911

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.

Upvotes: 1

Related Questions