1

I have an array:

$my_array = array(1 => 'has value', 2 =>'', 3 => '');

I want to run a if statment to check if all key have value or not, if there is not any value for all keys then return false

like:

if(any_key_has_value($my_array)){
    //run my query
}
0

4 Answers 4

3

If you define "has value" as "value == true":

if (count(array_filter($array)) == count($array)) {
    echo 'All elements have values';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Check with $settings=array('host'=>'localhost','user'=>true,'password'=>true,'database'=>true); and get true :P
1
function hasValue($v) {
    return strval($v) != '';
}    
$res_array = array_filter($my_array, 'hasValue');
// any key has value
$any_key_has_value = 0 < sizeof($res_array);
// all keys have values
$all_keys_have_values = sizeof($my_array) == sizeof($res_array);

Comments

1
$my_array = array(1 => 'has value', 2 =>'', 3 => '');

simply try this

if (array_filter($my_array)) {
    // here  first value  `has value` 
}else{
 // all values are empty 
}

Comments

1

Try this:

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

        if (!array_filter($array)) {

            echo "All keys have null values";
        }
        else
        {
               // do something
        }
        ?>

-

Comments

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.