当前位置:  首页>> 技术小册>> PHP合辑3-数组函数

key()函数是PHP中的一个内置函数,用于返回内部指针当前指向的给定数组的元素的索引。当前元素可能是起始元素或下一个元素,这取决于光标位置。默认情况下,光标位置位于零索引处,即位于给定数组的起始元素处。

语法:

key($array)

参数:该函数接受一个参数$array。它是我们想要找到由内部指针指向的当前元素所在的数组。

返回值:它返回给定数组的当前元素的索引。如果输入数组为空,则key()函数将返回NULL。


下面这个程序说明了PHP中的key()函数:

  1. <?php
  2. // input array
  3. $arr = array("Ram", "Geeta", "Shita", "Ramu");
  4. // Here key function prints the index of
  5. // current element of the array.
  6. echo "The index of the current element of".
  7. " the array is: " . key($arr);
  8. ?>

output:

  1. The index of the current element of the array is: 0

示例2

  1. <?php
  2. // input array
  3. $arr=array("Ram", "Geeta", "Shita", "Ramu");
  4. // next function increase the internal pointer
  5. // to point next to the current element.
  6. next($arr);
  7. // Here key function prints the index of
  8. // the current element of the array.
  9. echo "The index of the current element of".
  10. " the array is: " . key($arr);
  11. ?>

output:

  1. The index of the current element of the array is: 1

示例3:

  1. <?php
  2. // input array
  3. $arr = array("0", "F", "D", "4");
  4. // using next() function to increment
  5. // internal pointer two times
  6. next($arr);
  7. next($arr);
  8. // Here key function prints the index of
  9. // element of the current array position.
  10. echo "The index of the current element of".
  11. " the array is: " . key($arr);
  12. ?>

output:

  1. The index of the current element of the array is: 2