Home > Article > Backend Development > How to get the value of array key in php
In PHP, to obtain the value of the array Key, you need to use an associative array. An associative array is an array that stores data using key-value pairs, and the corresponding value can be obtained through the key.
The following introduces several methods of obtaining the Key value of the array.
Method 1: Use the array_keys() function
The array_keys() function can return a new array composed of all the keys in the array.
For example:
$array = array('name' => 'Tom', 'age' => 18); $keys = array_keys($array); print_r($keys); //输出 Array ( [0] => name [1] => age )
You can see that all key names in the array can be obtained through the array_keys() function.
Method 2: Use foreach loop
The foreach loop can traverse each element in the array, and the foreach loop can be used to obtain all key-value pairs in the array.
For example:
$array = array('name' => 'Tom', 'age' => 18); foreach ($array as $key => $value) { echo "Key: $key, Value: $value <br />"; }
As you can see, you can use the foreach loop to get the key name and key value of each element in the array.
Method 3: Use the array_key_exists() function
The array_key_exists() function can determine whether the specified key name exists in the array.
For example:
$array = array('name' => 'Tom', 'age' => 18); if (array_key_exists('name', $array)) { echo "The key 'name' exists in the array. <br />"; } else { echo "The key 'name' does not exist in the array."; }
You can see that using the array_key_exists() function can determine whether the specified key name exists in the array.
Method 4: Use isset() function
isset() function can determine whether the variable has been set and is not empty.
For example:
$array = array('name' => 'Tom', 'age' => 18); if (isset($array['name'])) { echo "The key 'name' exists in the array. <br />"; } else { echo "The key 'name' does not exist in the array."; }
You can see that the isset() function can be used to determine whether the specified key name has been set and is not empty.
Summary
The above are four ways to obtain the Key value in the array. We can flexibly use the above methods according to different situations to obtain the required array key name more accurately.
The above is the detailed content of How to get the value of array key in php. For more information, please follow other related articles on the PHP Chinese website!