如何检查关联数组是空还是null

时间:2016-06-09 09:38:14

标签: php arrays

我想计算多项选择的总分,一切运行良好但问题是如何验证单选按钮的多项选择问题,或者只检查关联数组是否为空,然后执行下面的代码。我已检查以下链接here但未通过

<?php   
    if(isset($_POST['btn_sectionA'])){
    $id = $_POST['test_id'];
    echo "<br>Test ID".$id."<br>";


    $sql = "SELECT  multiple_choice.mul_question_number,  multiple_choice.mul_que_body,  multiple_answer.A,  multiple_answer.B,  multiple_answer.C,  multiple_answer.D,  multiple_answer.option_Answer\n"
        . "FROM  multiple_answer\n"
        . "JOIN multiple_choice ON multiple_choice.mul_question_number =  multiple_answer.question_number\n"
        . "WHERE multiple_choice.test_id =".$id." AND multiple_answer.test_id =".$id."";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            echo '<form method="POST" action="../function/sectionA.php">'; // 
            while($row = mysqli_fetch_assoc($result)) {

                echo "Question :".$row["mul_question_number"]." ".$row["mul_que_body"]."<br>";
                echo 'A:<input type="radio" name="answer2question['.$row["mul_question_number"].']" value="A"> '.$row["A"].'<br>';
                echo 'B:<input type="radio" name="answer2question['.$row["mul_question_number"].']" value="B"> '.$row["B"].'<br>';
                echo 'C:<input type="radio" name="answer2question['.$row["mul_question_number"].']" value="C"> '.$row["C"].'<br>';
                echo 'D:<input type="radio" name="answer2question['.$row["mul_question_number"].']" value="D"> '.$row["D"].'<br><hr>';


            }
        }

    echo '<input type="hidden" value="'.$id.'" name="test_id"><input type="submit" value="Submit section A" name="btn_sectionA"></form>';

    }else{
      echo "failed to get questions";
    }

?> 

bove代码将发布到此页面和一些代码

foreach($_POST['answer2question'] as $question_number =>$given_answer){

   echo  "number: ".$question_number." answer:".$given_answer."<br>";

 $question_number  = mysqli_real_escape_string ($conn, $question_number);
    $given_answer = mysqli_real_escape_string ($conn, $given_answer);


 $sqlquery = "SELECT question_number FROM multiple_answer WHERE question_number = ".$question_number." AND option_Answer ='".$given_answer."' AND test_id = 1";
 $query = mysqli_query($conn,$sqlquery);
    if( mysqli_num_rows($query)!== 0 ){
        $score += 1;
    }

}

2 个答案:

答案 0 :(得分:2)

您可以使用is_array和/或count检查以下数组:

if (is_array($var) === true && count($var) > 0) {
    //here your code
}

//or...

if ((count($var) < 1) === false) {
    //here your code
}

在第一个条件:不要只使用count,因为:

  

如果参数不是数组,或者不是具有已实现Countable接口的对象,则返回1。有一个例外,如果array_or_countable为NULL,则返回0。   http://php.net/manual/en/function.count.php

答案 1 :(得分:0)

尝试这种方式。

$arr = [ 'key' => NULL ];

var_dump(array_key_exists('key', $arr));
var_dump(isset($arr['key']));

检查:

if(array_key_exists($key, $arra) && is_null($arr[$key]))
{
    echo 'key exists with NULL value';
}