PHP 中的 key() 函数

phpprogrammingserver side programming更新于 2025/8/9 11:22:17

key() 函数从数组中获取键。它返回内部指针指向的数组元素的键。

语法

key(arr)

参数

  • arr − 待使用的数组。

返回

key() 函数返回内部指针指向的数组元素的键。

示例

下面是一个例子 −

<?php
$arr = array("Electronics","Footwear");
echo "Key from the current position = " . key($arr);
?>

输出

Key from the current position = 0

示例

让我们看另一个例子 −

<?php
$arr = array(
'one' => 'tim',
'two' => 'peter',
'three' => 'david');
while ($val = current($arr)) {
   if ($val == 'peter') {
      echo key($arr);
   }
   next($arr);
}
?>

输出

two

相关文章