Tác dụng của hàm key()
The key()
function fetch the key or index of the current element in an array.
The following table summarizes the technical details of this function.
Return Value: | Returns the key of the current element in an array. Returns NULL if the array is empty or array's internal pointer points beyond the end of the elements list. |
---|---|
Changelog: | Since PHP 7.0.0, array is always passed by value to this function. Prior to this version, it was passed by reference if possible, and by value otherwise. |
Version: | PHP 4+ |
Tip: Every array has an internal pointer that points to the current element in the array. When a new array is created, the current pointer is initialized to reference the first element in the array.
Syntax
The basic syntax of the key()
function is given with:
The following example shows the key()
function in action.
Example
Run this code »<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");
// Getting the current element's key
echo key($alphabets); // Prints: a
/* Moving the array's internal pointer to the next
element then fetch the key */
next($alphabets);
echo key($alphabets); // Prints: b
?>
Parameters
The key()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies the array to work on. |
More Examples
Here're some more examples showing how key()
function actually works:
You can also use this function with indexed array to fetch index of current element.
Example
Run this code »<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");
// Getting the current element's key
echo key($colors); // Prints: 0
/* Moving the array's internal pointer to the next
element then fetch the key */
next($colors);
echo key($colors); // Prints: 1
?>
The key()
function is commonly used along with the following functions:
current()
– Returns the value of the current element in an array.next()
– Moves the internal pointer of an array to the next element, and returns its value.prev()
– Moves the internal pointer of an array to the previous element, and returns its value.end()
– Moves the internal pointer of an array to its last element, and returns its value.reset()
– Set the internal pointer of an array to its first element, and returns its value.
Here's an example that demonstrates how these functions basically work:
Example
Run this code »<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");
// Getting the values
echo current($colors); // Prints: red
echo end($colors); // Prints: black
echo current($colors); // Prints: black
echo prev($colors); // Prints: yellow
echo current($colors); // Prints: yellow
echo next($colors); // Prints: black
echo current($colors); // Prints: black
echo reset($colors); // Prints: red
echo current($colors); // Prints: red
// Getting the current element's key
echo key($colors); // Prints: 0
?>