Two detection methods: 1. Use array_key_exists() detection, the syntax "array_key_exists (specify key, specify array)", if the key exists, return true, if the key does not exist, return false. 2. Use the "$array name["specified key"]" statement to access the specified array element, and then use the isset() function to detect whether the array element exists. The syntax is "isset($array name["specified key"])". If Returns TRUE if the key exists, otherwise returns FALSE.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php checks whether the specified key name exists There are two methods for specifying an array:
Directly use the array_key_exists() function
Use the isset() function with "$Specify the array variable name ["Specify the key name"]
" statement
Method 1: Use the array_key_exists() function
array_key_exists(specify key name, specify array)
The function can detect whether the specified key name exists in an array. If the key name exists, it returns true. If the key name does not exist, it returns false.
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1=>"1","a"=>"",2=>"2","b"=>0,"c"=>"blue"); var_dump($arr); if (array_key_exists("a", $arr)) { echo "指定键名'a' 存在于指定数组"; } else { echo "指定键名'a'不存在于指定数组"; } ?>
Method 2: Use the isset() function with the "array name["specified key name"]
" statement
Use $ to specify the array variable name ["specified key name"]
to access the specified array element,
Use isset( ) function detects whether the array element exists
If it exists and is not NULL, it returns TRUE, otherwise it returns FALSE.
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1=>"1","a"=>"",2=>"2","b"=>0,"c"=>"blue"); var_dump($arr); if (isset($arr["d"])) { echo "指定键名'd' 存在于指定数组"; } else { echo "指定键名'd'不存在于指定数组"; } ?>
Description:
##array_key_exists( ) Function checks whether the specified key name exists in an array
array_key_exists(key,array)
Description | |
---|---|
key | Required . Specifies the key name.|
array | Required. Specifies an array.
isset() The function is used to detect whether the variable has been set and is not NULL.
PHP Video Tutorial"
The above is the detailed content of How to detect whether a key exists in an array in php. For more information, please follow other related articles on the PHP Chinese website!