php中的array_key_exists与NULL值没有输出

I have the following query:

//product density
$stmt_density = $conn->prepare("SELECT density FROM product_density
WHERE product_id = :productid ");
$stmt_density->execute(array(':productid' => "$pid"));
$density = $stmt_density->fetchAll(); 

If density is not present the value will be "NULL".

var_dump($density);

gives following output:

array(1) { [0]=> array(2) { ["density"]=> NULL [0]=> NULL } } 

I need to check whether the array is having values or not and to provide select options, if array not empty.

Depending on whether you expect to get back multiple results from your query could change the answer, especially if you get back say 1 result with a NULL and one without. But you could do...

function validResult($density) {
    foreach($density as $item) {
        if($item["density"] == NULL) return false;
    }
    return true;
 }


 if(validResult($density))
     echo "We have values";
 else
     echo "Array contains null";

The function will return false if any result has null, regardless of how many are not null

Try something like this

function check($array, $key)
{
    if(array_key_exists($key, $array)) {
        if (is_null($array[$key])) {
            echo $key . ' is null';
        } else {
            echo $key . ' is set';
        }
    }
}

I think you are trying to check for null values in an array try

function array_key_exists_r($needle, $haystack)
{
    foreach ($haystack as $v) {
        foreach ($v as $k=>$v1) {
            if(empty($v1) || $v1 ==$needle)
              $result[$k] = $v1;
        }
        if ($result) return $result;
    }
}
$r = array_key_exists_r('NULL', $density);
print_r($r); //Array ( [density] => [0] => ) 

Function will give you all empty or NULL keys as an array