Two detection methods: 1. Use array_key_exists() to detect, the syntax is "array_key_exists (subscript value, array)". 2. Use array_keys() to obtain all subscripts (key names) of the original array and return an array of key names. Use array_search() to search for the specified value in the key name array. The syntax is "array_search("a", array_keys(original Array))", returns the corresponding key name if it exists, returns FALSE if it does not exist.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
Array array is a set of ordered variables. Each value is called an element. Each element is distinguished by a special identifier called a key (also called a subscript).
Each entity in the array contains two items, namely key and value. The corresponding array elements can be obtained by key value. These keys can be numeric keys or association keys. If a variable is a container that stores a single value, then an array is a container that stores multiple values.
Two methods for php to detect whether the specified subscript exists in an array
##Method 1: Use the array_key_exists() function to detect
array_key_exists() 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.array_key_exists(key,array)
Description | |
---|---|
key | Required . Specifies the key name.|
array | Required. Specifies an array.
<?php header('content-type:text/html;charset=utf-8'); $arr=array("a"=>"Dog","b"=>"Cat"); var_dump($arr); if (array_key_exists("a",$arr)){ echo "指定下标'a'存在!"; }else { echo "指定下标'a'不存在"; } ?>
Method 2: Use array_keys() and array_search() to detect
<?php header('content-type:text/html;charset=utf-8'); $arr=array("a"=>"Dog","b"=>"Cat"); echo "原数组:"; var_dump($arr); $keys=array_keys($arr); echo "键名数组:"; var_dump($keys); var_dump(array_search("a",$keys)); var_dump(array_search("b",$keys)); var_dump(array_search("c",$keys)); ?>
PHP Video Tutorial"
The above is the detailed content of How to detect whether a specified subscript exists in an array in php. For more information, please follow other related articles on the PHP Chinese website!