PHP - 如何检查空数组?

时间:2016-06-02 20:17:01

标签: php arrays if-statement foreach

好的,这很容易,但我不知道为什么我的不检查它!

我有一个if statement来检查一个数组是否为空,如果它是空的,它应该跳过它,但所有的尝试都不会跳过它。

以下是代码:

$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++;

    }

}

以下是我需要跳过的结果:

---->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) { } 

我如何跳过此数组?

1 个答案:

答案 0 :(得分:1)

  

以下内容被认为是空的:

"" (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)

这是以下页面的引用:

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

您的代码将$quizData['marks']视为空的原因是因为$quizData['marks']中的变量等于零。如果添加另一个不为零的值,则代码应该可以正常工作。

也许考虑添加:

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