$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?
答案 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。