Home > Article > Backend Development > How to detect whether an array contains a specified key in php
Two methods: 1. Use the "array_key_exists("key name", array)" statement. If it is included, it will return true, otherwise it will not be included. 2. Use isset() to detect whether the element corresponding to the specified key name exists. The syntax is "isset($array name["key name"])". If it is included, it returns true, otherwise it is not included.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php detection array Whether to include two methods of specifying keys
1. Use the array_key_exists() function
array_key_exists($key,$array)
The function checks 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"); $a=array("Volvo"=>"XC90","BMW"=>"X5"); if (array_key_exists("Toyota",$a)) { echo "指定键存在"; } else { echo "指定键不存在"; } ?>
2. Use the isset() function
isset() function is used to detect whether the variable has been set and is not NULL.
Just use the isset() function to detect whether the specified array element $array["key name"]
exists.
<?php header("Content-type:text/html;charset=utf-8"); $a=array("Volvo"=>"XC90","BMW"=>"X5"); if (isset($a["BMW"])) { echo "指定键存在"; } else { echo "指定键不存在"; } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to detect whether an array contains a specified key in php. For more information, please follow other related articles on the PHP Chinese website!