Home  >  Article  >  Backend Development  >  PHP returns the key name currently pointed to by the internal pointer of the array

PHP returns the key name currently pointed to by the internal pointer of the array

WBOY
WBOYforward
2024-03-21 16:21:061202browse

php editor Baicao today introduces to you a commonly used function in PHP, which is the array_key function. The array_key function is used to return the key name currently pointed to by the internal pointer of the array. This function is very useful when processing arrays, and can help us operate the key names and key values ​​of the array more flexibly. In PHP development, proficient use of the array_key function can improve the efficiency and readability of the code. It is a skill worth mastering.

PHP returns the key name currently pointed to by the internal pointer of the array

php provides a function called key(), which is used to return the key name currently pointed to by the internal pointer of the array. This function works on indexed arrays and associative arrays.

grammar

key(array)

parameter

  • array: The array from which the key names are to be obtained.

return value

  • The key name currently pointed by the internal pointer. If it is an index array, the integer index is returned; if it is an associative array, the string key name is returned.
  • If the array is empty or the internal pointer points to the end of the array, NULL is returned.

usage

<?php
// index array
$arr = ["apple", "banana", "cherry"];
$key = key($arr); // 0

//Associative array
$arr = ["fruit" => "apple", "vegetable" => "carrot"];
$key = key($arr); // "fruit"
?>

Example

<?php
$arr = ["apple", "banana", "cherry"];

// Use key() to get the current key name
$key = key($arr);
echo $key; // 0

//Move the internal pointer to the next element
next($arr);
$key = key($arr);
echo $key; // 1

//Reset the internal pointer to the first element
reset($arr);
$key = key($arr);
echo $key; // 0
?>

Other notes

  • If the array is a multi-dimensional array, key() will return the key name of the current dimension.
  • If the array contains a null value, key() will skip the null value and return the key name of the next non-empty element.
  • key() Used in conjunction with the current() function, you can get the key name and value of the current element in the array.
<?php
$arr = ["apple", "banana", "cherry"];

$key = key($arr);
$value = current($arr);

echo "$key: $value"; // 0: apple
?>

The above is the detailed content of PHP returns the key name currently pointed to by the internal pointer of the array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete