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