22

I have an array

$array = array('key1' => null, 'key2' => null, 'key3' => null, 'key4' => null);

i would like to determine if all the array keys have empty values if so then return false. the above example should return false as it does not have any value. but if one or more keys have any values then it should return true for example the below example is true.

$array = array('value1', 'key2' => value2, 'value3', 'key4' => value4);
2
  • 1
    All the keys do have values, the keys just aren't what you think they are. Array ( [0] => key1 [1] => key2 [2] => key3 [3] => key4 ) and Array ( [0] => key1 [key2] => value2 [1] => key3 [key4] => value4 ) respectively. Commented Jun 14, 2011 at 6:12
  • sorry, i knew that, and i was missing the point :) Commented Jun 14, 2011 at 6:15

4 Answers 4

59

Assuming you actually mean an array like

array('key1' => null, 'key2' => null, 'key3' => null, 'key4' => null)

the answer is simply using array_filter

if (!array_filter($array)) {
    // all values are empty (where "empty" means == false)
}
Sign up to request clarification or add additional context in comments.

Comments

4

Your assumption is incorrect. array('key1', 'key2', 'key3', 'key4') has 4 values and keys in the range 0..3.

array('key1', 'key2' => value2, 'key3', 'key4' => value4) has the value key1 (with key 0), the key key2, the value key3 (with key 1) and the key key4.

1 Comment

@Ibrahim: try print_r($array) then you should see how you array looks like. blagovest is completly right.
1

If you need to check if all values are null

$allNull = true;
foreach( $array as $key => $val ) {
    if( is_null( $array[$key] ) ) {
        $allNull = false;
        break;
    }
}

// Do what you will with $allNull

Comments

0
$array = array('key1' => null, 'key2' => null, 'key3' => null, 'key4' => null);

The answer is

$filterArray = array_filter($array);

if(count($filterArray) == 0){
    return false;
}else{
    return true;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.