array_key_exists() function in PHP: How to check whether the specified key exists in the array
In the PHP language, the array is a very important data structure , which can store any type of data, and can access and operate elements in the array through key names. However, when we need to determine whether a specified key name exists in an array, how to achieve it?
In PHP, there is a built-in function-array_key_exists(), which can easily check whether a specified key name exists in an array. The basic syntax of this function is as follows:
bool array_key_exists ( mixed $key, array $array )
Among them, $key represents the key name to be checked, which can be any type of value, and $array represents the array to be checked. The return value of this function is a Boolean value. If the key name exists in the array, it returns true, otherwise it returns false.
Below, let’s give a specific example to show how to use the array_key_exists() function to check whether the specified key name exists in the array.
<?php // 定义一个关联数组 $arr = array( 'name' => '张三', 'age' => 18, 'address' => '北京市朝阳区' ); // 判断数组中是否存在指定的键名 if (array_key_exists('age', $arr)) { echo '该数组中存在age键名。'; } else { echo '该数组中不存在age键名。'; } ?>
In the above example, we define an associative array $arr and use the array_key_exists() function to determine whether the age key exists in the array. Since the age key name does exist in the array, executing this code will output:
该数组中存在age键名。
In addition to associative arrays, the array_key_exists() function can also be used to check whether the specified key exists in the properties of ordinary arrays and objects. name. Next, let’s look at a specific example.
<?php // 定义一个普通数组 $arr = array(1, 2, 3, 4, 5); // 判断数组中是否存在指定的键名 if (array_key_exists(2, $arr)) { echo '该数组中存在下标为2的元素。'; } else { echo '该数组中不存在下标为2的元素。'; } ?>
In the above example, we define a normal array $arr and use the array_key_exists() function to determine whether there is an element with index 2 in the array. Since the element with subscript 2 does exist in the array, executing this code will output:
该数组中存在下标为2的元素。
Summary
array_key_exists() function can be used to check whether the specified key exists in an array name, its use is very simple, you only need to pass in the corresponding key name and array. In addition to associative arrays, this function can also be used to check whether the specified key exists in the properties of ordinary arrays and objects.
The above is the detailed content of Array_key_exists() function in PHP: How to check whether a specified key name exists in an array. For more information, please follow other related articles on the PHP Chinese website!