簡體   English   中英

如何檢測數組中的空值或未設置鍵?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM