Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there are any array values set PHP

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.

like image 637
Dylan Cross Avatar asked Dec 21 '22 13:12

Dylan Cross


1 Answers

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.

like image 107
nickb Avatar answered Jan 04 '23 23:01

nickb