要确定关联数组是否有键,您可以使用 array_key_exists()
函数或 isset()
函数。这两个函数都可以检查关联数组中是否存在指定的键。
array_key_exists()
函数接受两个参数:键名和数组。如果键名存在于数组中,则返回 true
,否则返回 false
。
例如:
$array = [
'key1' => 'value1',
'key2' => 'value2',
];
if (array_key_exists('key1', $array)) {
echo 'Key1 exists in the array.';
} else {
echo 'Key1 does not exist in the array.';
}
isset()
函数接受一个或多个参数,可以检查多个变量是否已设置。如果变量已设置且不为 null
,则返回 true
,否则返回 false
。
例如:
$array = [
'key1' => 'value1',
'key2' => 'value2',
];
if (isset($array['key1'])) {
echo 'Key1 exists in the array.';
} else {
echo 'Key1 does not exist in the array.';
}
这两个函数都可以用来检查关联数组中是否存在指定的键。您可以根据自己的需要选择使用哪个函数。
领取专属 10元无门槛券
手把手带您无忧上云