Two detection methods: 1. Use the array_key_exists() function to check whether the specified index exists in the array. The syntax is "array_key_exists (specified index value, array)". If the return value is true, it exists, otherwise it does not. exist. 2. Use the isset() function to detect whether the array element corresponding to the specified index exists. The syntax is "isset($array name[specified index value])". If the return value is true, it exists, otherwise 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 or index).
The index of the array refers to the position of the current array element in the array (an integer value starting from 0).
So how to detect whether the specified index in the PHP array exists?
php To detect whether the specified index exists, you can use the array_key_exists() function or isset() function.
Method 1. Use array_key_exists() function
array_key_exists() function checks whether the specified key name exists in an array. If the key name exists, Returns true, or false if the key name does not exist.
array_key_exists($key,$array)
Parameters | Description |
---|---|
key | Required . Specifies the key name. |
array | Required. Specifies an array. |
Therefore, you only need to set the first parameter of the function to the specified index value.
<?php header('content-type:text/html;charset=utf-8'); function f($a,$v){ if (array_key_exists($v,$a)) { echo "指定索引 $v 存在<br>"; } else { echo "指定索引 $v 不存在<br>"; } } $arr=array(1=>11,3=>33,4=>44,5=>55,6=>66); var_dump($arr); f($arr,2); f($arr,4); ?>
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[index value]
exists.
<?php header('content-type:text/html;charset=utf-8'); function f($a,$v){ if (isset($a[$v])) { echo "指定索引 $v 存在<br>"; } else { echo "指定索引 $v 不存在<br>"; } } $arr=array(1=>11,3=>33,5=>55,7=>77); var_dump($arr); f($arr,2); f($arr,4); f($arr,5); f($arr,7); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to detect whether the specified index exists in a php array. For more information, please follow other related articles on the PHP Chinese website!