[英]How to detect the empty value or unset key in array?
$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?
在大多數情況下, 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
您可以改用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];
}
如果不存在數組鍵或存在空值的數組鍵,則empty
將返回true。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.