Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何检测数组中的空值或未设置键?_Php_Arrays - Fatal编程技术网

Php 如何检测数组中的空值或未设置键?

Php 如何检测数组中的空值或未设置键?,php,arrays,Php,Arrays,用于检测值的代码是未设置的或空的,有时键的值不是空的,但它总是返回true?isset在大多数情况下都可以,数组键存在更“准确”,因为它也会检测设置的空值(而不是根本没有设置) $requiredKey = ['name', 'type', 'costPrice', 'salePrice']; $newArr = ["costPrice" => "45", "name" => "133", "productType" => "456",

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

isset
在大多数情况下都可以,数组键存在更“准确”,因为它也会检测设置的空值(而不是根本没有设置)

$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];
}

isset
在大多数情况下都可以,
array\u key\u exists
更“准确”,因为它还可以检测设置的空值(而不是根本不设置)

$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];
}

您可以改为使用
empty

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
将返回true。

您可以改用
empty

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
如果数组键不存在或数组键存在且值为空,将返回true。

您可以使用
isset
array\u key\u exists
检查数组中的某个键。
如果(!isset($newArr[$key])回显“值未设置”
如果(!array\u key\u exists($key,$newArr))回显“键在数组中不存在”
有关
数组\u键存在的详细信息
:您的代码为我返回false。这种类型的检查确实会像预期的那样抛出未定义的索引,但它确实返回false。您可以使用
isset
数组\u键存在
来检查数组中的某个键。
如果(!isset($newArr[$Key])echo”值未设置“
如果(!array\u key\u exists($key,$newArr))echo”键在数组中不存在"
有关
数组_key_exists的详细信息
:您的代码为我返回false。它确实会像这种类型的检查一样抛出一个未定义的索引,但它确实返回false。请记住,如果使用empty,除了null之外还有许多其他值被视为空。只要记住,如果使用empty,还有许多其他值被视为空IDE被认为是空的。