4

What's the best/easiest way to check if an array has any values set? I set the keys myself, no matter what so I can't go based on the keys. My code will show what I'm doing, and want to do:

 $array = array(
                "Birthday" => $row3['birthday'],
                "Sex" => $row3['sex'],
                "Lives In" => $row3['livesIn']
            );
    if(empty($array))
    {
        foreach($array as $key => $value)
        {
            if($value)
            {       
                echo "<tr><td>".$key."</td><td>".$value."</td></tr>";   
            }
        }
    }
    else
    {
        echo "This user has not provided any information yet";  
    }

So, for instance, if $row3['birthday'], $row3['sex'], $row3['livesIn'] are all empty, then it should render the first if statement as false, and move to the else statement.

1
  • 3
    This question is kinda old, but it helped me, and it is actually NOT a duplicate of the marked question. The possible duplicate question is asking how to find if there are any empty values in an array, whereas this question asks how to find if there are any non-empty values. The solution in the marked question cannot be applied to this question. The accepted answer on this question works. Commented Oct 8, 2013 at 13:38

1 Answer 1

11

I believe you're looking for array_filter(), which with one parameter will remove all array values that are equal to false when typecasted to a boolean:

if( count( array_filter( $array)) == 0) {
    echo "Array contained 'empty' values\n";
}

You can see the manual to find out which values will become boolean false.

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

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.