array_key_first
(PHP 7 >= 7.3.0, PHP 8)
array_key_first — 获取指定数组的第一个键
参数
array
-
要操作的数组。
返回值
如果 array
不是空的,返回第一个键,否则返回 null
。
示例
示例 #1 array_key_first() 基本用法
<?php
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$firstKey = array_key_first($array);
var_dump($firstKey);
?>
以上示例会输出:
string(1) "a"
注释
小技巧
在 PHP 7.3.0 之前,有几种方式可以实现该功能。可以使用 array_keys() 函数,但是性能会比较低。也可以使用 reset() 和 key() 函数,但这可能会影响内部数组指针。实现该功能的 polyfill 写法如下:
<?php
if (!function_exists('array_key_first')) {
function array_key_first(array $arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
}
?>
参见
- array_key_last() - 获取一个数组的最后一个键值
- reset() - 将数组的内部指针指向第一个单元
+添加备注
用户贡献的备注 1 note
MaxiCom dot Developpement at gmail dot com ¶
1 year ago
A polyfill serves the purpose of retroactively incorporating new features from PHP releases into older PHP versions, ensuring API compatibility.
In PHP 7.3.0, the array_key_first() function was introduced, demonstrated in the following example:
<?php
$array = [
'first_key' => 'first_value',
'second_key' => 'second_value',
];
var_dump(array_key_first($array));
?>
The provided polyfill in this documentation allows the convenient use of array_key_first() with API compatibility in PHP versions preceding PHP 7.3.0, where the function was not implemented:
<?php
if (!function_exists('array_key_first')) {
function array_key_first(array $arr) {
foreach ($arr as $key => $unused) {
return $key;
}
return null;
}
}
$array = [
'first_key' => 'first_value',
'second_key' => 'second_value',
];
var_dump(array_key_first($array));
?>
备份地址:http://www.lvesu.com/blog/php/function.array-key-first.php