如何检测数组中的空值或取消设置键?

时间:2017-07-20 15:28:22

标签: php arrays

$requiredKey = ['name', 'type', 'costPrice', 'salePrice'];  
$newArr = ["costPrice" => "45",
        "name" => "133",
        "productType" => "456",
        "remark" => "4545",
        "salePrice" => "454545",
        "saleType" => "789"];
foreach ($requiredKey as $key) {
    if($newArr[$key] == null) {
        //Why this place always is true?
        echo 'null';
        return false;
    }
    $insertData[$key] = $newArr[$key];
}

用于检测值的代码是未设置或为空,有时key的值不为空,但它总是返回true?

2 个答案:

答案 0 :(得分:0)

isset在大多数情况下都会这样做,array_key_exists更“准确”,因为它也会检测到设置的空值(而不是根本不设置。

isset($a['x']) --> false
array_key_exist('x', $a) --> false
$a['x'] = 1;
isset($a['x']) --> true
array_key_exist('x', $a) --> true
$a['x'] = null;
isset($a['x']) --> false
array_key_exist('x', $a) --> true

答案 1 :(得分:0)

您可以改用empty

$requiredKey = ['name', 'type', 'costPrice', 'salePrice'];  
$newArr = ["costPrice" => "45",
        "name" => "133",
        "productType" => "456",
        "remark" => "4545",
        "salePrice" => "454545",
        "saleType" => "789"];
foreach ($requiredKey as $key) {
    if(empty($newArr[$key])) {
        echo 'null';
        return false;
    }
    $insertData[$key] = $newArr[$key];
}
如果数组键不存在或者数组键存在且值为null,则

empty将返回true。