25

Here is my array ouput

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

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

foreach ($array as $key => $value) {
    if (empty($value))
        echo "$key empty <br/>";
    else
        echo "$key not empty <br/>";
}

My out put showing all is not empty. What is correct way to check is empty?

2
  • 1
    Maybe because the third element is a white space ' ', so it's not an empty string? If so, try change it in if (trim($value) != '')... Commented Feb 20, 2012 at 19:48
  • 3
    To avoid these issues, use var_dump() when printing out values. It will show the length and not hide those blank characters. Commented Feb 20, 2012 at 19:51

8 Answers 8

37

Another solution:

$array = array('one', 'two', '');

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

http://codepad.org/zF9KkqKl

Also,

$containsEmpty = in_array("", $arr);

Should be a bit faster as it doesn't have to trace the entire array and doesn't have to create a new array.

Note that both solutions will consider 0, false, null and empty array as empty values as well.

In case you also consider a value empty if it consists of space-like characters only, see the answer below

Sign up to request clarification or add additional context in comments.

1 Comment

If the task is merely to determine if any element has a zero-length value, then !strlen() should be used, then a break or return or exit (depending on context) to avoid doing unnecessary iterations.
24

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 ($value === '')
        echo "$key is empty <br/>";
    else
        echo "$key is not empty <br/>";
}

Or to make it a function

function arrayHasEmptyValue(array $array) {    
    foreach ($array as $value) {
        if (trim($value) === '') {
            return true;
        }
    }
    return false;
}

1 Comment

$key doesn't need to be declared in the second snippet because it is never used.
10

For a different task, when you need to tell if ALL array values are empty, you can use the following:

if (array_filter($array)) {
    echo 'OK';
} else {
    echo 'EMPTY ARRAY';
}

1 Comment

This looks like the correct answer to a different question. If only readers bothered to compare the asked question with the functionality of the answer before voting. :(
3

In case you also consider values empty if they contain only spaces, like below

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

here is the solution

if(in_array('', array_map('trim', $myArray), true)) {
   echo 'Found empty value in your array!';
}

1 Comment

This answer makes two passes over the input and does not have the ability to "short circuit" as a way to improve performance.
1

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.

2 Comments

This doesnt works .. php> print_r($array); Array ( [0] => one [1] => two [2] => ) php> $emptyKeys = array_diff_key(array_diff($array,array()),$array); php> print_r($emptyKeys); Array ( )
Even if this answer worked as expected in all scenarios, why would someone want to use two iterators when never more than one full iteration is necessary???
1

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!';
        }

1 Comment

So you are demonstrating how both of these native functions perform loose comparisons?
0

im using in my project like this for check this array

im posting form data like this array('username' => 'john','surname' => 'sins');

public function checkArrayKeyExist($arr) {
    foreach ($arr as $key => $value) {
        if (!strlen($arr[$key])) {
            return false;
        }
    }
    return true;
}

3 Comments

add some explanation
im added some explanation
$arr[$key] is more simply expressed as $value. The $key declaration is not necessary since it is not returned. checkArrayKeyExist() is a very poor/misleading choice for a method name.
-1

Try this:

<?php
    $data=array(
        'title' => 'Test Name Four',
        'first_name' => '',
        'last_name' => 'M',
        'field_company' => 'ABC',
        'email' => '',
        'client_phone_number' => '',
        'address_line_1' => '',
        'address_line_2' => 'Address 3',
        'address_line_3' => '',
        'address_line_4' => '',
        'post_code' => '',
        );
    echo '<pre>';
    print_r($data);
    foreach ($data as $key => $case ) { 
        echo "$key => ".is_multiArrayEmpty($case)."<br>"; 
    }
    function is_multiArrayEmpty($multiarray) { 
        if(is_array($multiarray) and !empty($multiarray)){ 
            $tmp = array_shift($multiarray); 
                if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){ 
                    return false; 
                } 
                return true; 
        } 
        if(empty($multiarray)){ 
            return true; 
        } 
        return false; 
    } 
?>

1 Comment

What is the point of this unexplained recursive snippet dump? Did you read the question and its sample data?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.