key()函数是PHP中的一个内置函数,用于返回内部指针当前指向的给定数组的元素的索引。当前元素可能是起始元素或下一个元素,这取决于光标位置。默认情况下,光标位置位于零索引处,即位于给定数组的起始元素处。
语法:
key($array)
参数:该函数接受一个参数$array。它是我们想要找到由内部指针指向的当前元素所在的数组。
返回值:它返回给定数组的当前元素的索引。如果输入数组为空,则key()函数将返回NULL。
下面这个程序说明了PHP中的key()函数:
<?php
// input array
$arr = array("Ram", "Geeta", "Shita", "Ramu");
// Here key function prints the index of
// current element of the array.
echo "The index of the current element of".
" the array is: " . key($arr);
?>
output:
The index of the current element of the array is: 0
示例2
<?php
// input array
$arr=array("Ram", "Geeta", "Shita", "Ramu");
// next function increase the internal pointer
// to point next to the current element.
next($arr);
// Here key function prints the index of
// the current element of the array.
echo "The index of the current element of".
" the array is: " . key($arr);
?>
output:
The index of the current element of the array is: 1
示例3:
<?php
// input array
$arr = array("0", "F", "D", "4");
// using next() function to increment
// internal pointer two times
next($arr);
next($arr);
// Here key function prints the index of
// element of the current array position.
echo "The index of the current element of".
" the array is: " . key($arr);
?>
output:
The index of the current element of the array is: 2