Home >Backend Development >PHP Problem >PHP array learning: extract the key name of the first element of the associative array
In the previous article, we introduced the method of using PHP to modify the key names of one-dimensional arrays and two-dimensional arrays. If you are interested, you can click on the link to read → "PHP Array Learning: Changing One-Dimensional and Two-Dimensional Arrays The key key》. This time we continue to talk about the key names of the array and introduce how to get the first key value of the array. If you need it, you can learn more~
→Related recommendations: 《 Summary of PHP array learning series (continuously updated~) 》
Today, this article will introduce to you 3 methods of obtaining the first key value of an array. Let’s take a look!
Method 1: Use the array_key_first() function
The function of the array_key_first() function is to return the first key name key of the specified array .
Syntax: array_key_first ($array)
Let’s take a look at the implementation code:
<?php header("content-type:text/html;charset=utf-8"); $array = ['a' => 1, 'b' => 2, 'c' => 3]; $firstKey = array_key_first($array); echo "数组第一个键名为:".$firstKey; ?>
The output result is:
Method 2: Use reset() key() function
key($array )
function can get the key name of the current array element. We can first use the reset($array)
function to point the internal pointer of the array to the first element of the array (at this time, the first element is the current element), then use key() to get the first key name of the array.
Let’s take a look at the implementation code:
<?php header("content-type:text/html;charset=utf-8"); $array = ['a' => 1, 'b' => 2, 'c' => 3]; reset($array); $firstKey = key($array); echo "数组第一个键名为:".$firstKey; ?>
The output result is:
Method 3: Using array_keys () Function
array_keys() function can return a new array containing all the key names in the array; then the first element of this key array is the first key of the original array name.
Let’s take a look at the implementation code:
<?php header("content-type:text/html;charset=utf-8"); $array = ['a' => 1, 'b' => 2, 'c' => 3]; $keys=array_keys($array); $firstKey = $keys[0]; echo "数组第一个键名为:".$firstKey; ?>
The output result is:
Okay, that’s all. If you want to know anything else, you can click here. → →php video tutorial
Finally, I would like to recommend a free video tutorial on PHP arrays: PHP function array array function video explanation, come and learn!
The above is the detailed content of PHP array learning: extract the key name of the first element of the associative array. For more information, please follow other related articles on the PHP Chinese website!