How do I check if array value is empty?

前端 未结 8 1720
天命终不由人
天命终不由人 2020-12-09 04:03

Here is my array ouput

Array
(
    [1] => 1
    [2] => 2
    [3] =>  
)

How do I know the [3] => is empty?

相关标签:
8条回答
  • 2020-12-09 04:19

    You can use array_diff() and array_diff_key():

    $array = array('one', 'two', '');
    $emptyKeys = array_diff_key(array_diff($array,array()),$array);
    

    array_diff() extracts all items which are not the same (therefore leaving out the blanks), array_diff_key gives back the differences to the original array.

    0 讨论(0)
  • 2020-12-09 04:21

    An other solution:

    $array = array('one', 'two', '');
    
    if(count(array_filter($array)) == count($array)) {
        echo 'OK';
    } else {
        echo 'ERROR';
    }
    

    http://codepad.org/zF9KkqKl

    0 讨论(0)
  • 2020-12-09 04:25

    It works as expected, third one is empty

    http://codepad.org/yBIVBHj0

    Maybe try to trim its value, just in case that third value would be just a space.

    foreach ($array as $key => $value) {
        $value = trim($value);
        if (empty($value))
            echo "$key empty <br/>";
        else
            echo "$key not empty <br/>";
    }
    
    0 讨论(0)
  • 2020-12-09 04:31

    You can check for an empty array by using the following:

    if ( !empty(array_filter($array))) {
        echo 'OK';
    } else {
        echo 'EMPTY ARRAY';
    }
    
    0 讨论(0)
  • 2020-12-09 04:32
    $array = array('A', 'B', ''); 
    

    or

    $array = array('A', 'B', '  ');
    

    An other solution:

    this work for me

    if(in_array(null, $myArray) || in_array('', array_map('trim',$myArray))) {
       echo 'Found a empty value in your array!';
       }
    
    0 讨论(0)
  • 2020-12-09 04:34

    Here is a simple solution to check an array for empty key values and return the key.

    $a = array('string', '', 5);
    
            echo array_search(null, $a);
            // Echos 1
    

    To check if array contains an empty key value. Try this.

            $b = array('string','string','string','string','','string');
    
            if (in_array(null, $b)) {
                echo 'We found a empty key value in your array!';
            }
    
    0 讨论(0)
提交回复
热议问题