Two methods: 1. Use "array_key_exists("specified key value", $arr)" and return true if it exists. 2. Use "isset($arr["specified key value"]" to check whether the value corresponding to the specified key name exists, and then determine whether the key exists. If it exists, it will return true.
The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer
Two methods for PHP to detect whether the array key exists:
1. Use array_key_exists() function
array_key_exists() function checks whether the specified key name exists in an array and returns true if the key name exists. , if the key name does not exist, return false.
<?php header('content-type:text/html;charset=utf-8'); $arr = array("Volvo" => "XC90", "BMW" => "X5"); if (array_key_exists("Volvo", $arr)) { echo "数组key存在!"; } else { echo "数组key不存在!"; } ?>
2. Use the isset() function
isset() function Used to detect whether the variable has been set and is not NULL.
Detection idea:
Use array name["key"]
to access the specified array element,
Use isset() function to detect whether the array element exists
If it exists and is not NULL, return TRUE, otherwise return FALSE.
<?php header('content-type:text/html;charset=utf-8'); $arr = array("Volvo" => "XC90", "BMW" => "X5"); if (isset($arr["a"])) { echo "数组key存在!"; } else { echo "数组key不存在!"; } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to detect whether array key exists in php. For more information, please follow other related articles on the PHP Chinese website!