简体   繁体   中英

PHP - How to check for an empty array?

Ok, this is easy, but I don't know why mine is not checking it!

I have an if statement that checks if an array is empty, if it's empty it should skip it, but all tries made not to skip it.

Here is the code:

$quizCounter = 0;
foreach ($quizzes as $key => $quiz) {

    if (!is_null($quiz['quiz_data'])) {

        echo "---->" . $key . "<BR>";

        unset($mark);
        $result = 0;
        $quizData = unserialize($quiz['quiz_data']);
        $quizTimestamp = date("d-m-Y", strtotime($quiz['time_stamp']));

        echo "Quiz: ";
        var_dump($quiz);
        echo "<BR>";

        echo "Quiz Data: ";
        var_dump($quizData);
        echo "<BR>";

        echo "Var Dump: ";
        var_dump($quizData['marks']);
        echo "<BR>";

        // Quiz marks
        if(!empty($quizData['marks'])) {
            foreach ($quizData['marks'] as $key => $marks) {
                $mark[$key] = $marks;
                echo "Mark: ";
                echo var_dump($marks) . "<BR>";
                $result += $marks;
            }
        }

        $markCounter = (count($mark) == 0) ? 1 : count($mark);
        $quizResult[$quizCounter] = $result / $markCounter;
        $quizCounter++;

    }

}

And here is the result that I need to skip:

---->34
Quiz: array(4) { ["quiz_data"]=> string(41) "a:2:{s:4:"ques";a:0:{}s:5:"marks";a:0:{}}" [0]=> string(41) "a:2:{s:4:"ques";a:0:{}s:5:"marks";a:0:{}}" ["time_stamp"]=> string(26) "0000-00-00 00:00:00.000000" [1]=> string(26) "0000-00-00 00:00:00.000000" } 
Quiz Data: array(2) { ["ques"]=> array(0) { } ["marks"]=> array(0) { } } 
Var Dump: array(0) { } 

How may I skip this array?

The following things are considered to be empty:

 "" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) $var; (a variable declared, but without a value) 

This is a quote from the following page:

http://php.net/manual/en/function.empty.php

The reason why your code considers $quizData['marks'] as empty is because you have a variable equal to zero in $quizData['marks'] . If you add another value that is not zero, your code should work.

Perhaps consider adding:

else if(isset($quizData['marks'])) {
    //proceed to print that person has a mark of zero
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM