(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;
}
}
?>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));
?>