编程

PHP 8.5:新增 array_first 和 array_last 函数

21 2025-06-17 03:10:00

PHP 8.5 预计将于 11 月发布,本系列将带你提前了解新版本功能。

PHP 8.5 添加了两个新函数,用于检索数组的第一个和最后一个值。这些函数补充了 PHP 7.3 中添加的 array_key_firstarray_key_last 函数。

  • array_first:从给定数组中检索第一个值;如果数组为空,则为 null
  • array_last:从给定数组中检索最后一个值;如果数组为空,则为 null

关于 null

请注意如果数组为空,这两个函数将返回 null。不过 null 本身也可以是有效的数组值。

array_first

array_first 函数返回给定数组的第一个数组值。在列表数组中,这基本上是键 0 的值。即使在关联数组上 array_first 也会返回第一个值。

/**
  * Returns the first value of a given array.
  *
  * @param array $array The array to get the first value of.
  * @return mixed First value of the array, or null if the array is
  *   empty. Note that null itself can also be a valid array value.
  */
function array_first(array $array): mixed {}

array_first 用例

array_first([1, 2, 3]); // 1
array_first([2, 3]); // 2
array_first(['a' => 2, 'b' => 1]); // 2
array_first([null, 2, 3]); // null
array_first([]); // null
array_first([$obj, 2, 3]); // $obj
array_first([1])); // 1
array_first([true]); // true

array_last

array_last 函数返回给定数组的最后一个数组的值。

/**  
 * Returns the first value of a given array. * * @param array $array The array to get the first value of.  
 * @return mixed First value of the array, or null if the array is  
 *   empty. Note that null itself can also be a valid array value.
 */
function array_last(array $array): mixed {  
  return empty($array) ? null : $array[array_key_last($array)];  
}

array_last 用例

array_last([1, 2, 3]); // 3
array_last([2, 3]); // 3
array_last(['a' => 2, 'b' => 1]); // 1
array_last([2, 3, null]); // null
array_last([]); // null
array_last([2, 3, $obj]); // $obj
array_last([1])); // 1
array_last([true]); // true

用户空间 PHP Polyfill

使用 PHP 7.3 中添加的 array_key_firstarray_key_last 函数,可以轻松地对新的两个函数进行 polyfill。

function array_first(array $array): mixed {  
  return $array === [] ? null : $array[array_key_first($array)];  
}
function array_last(array $array): mixed {  
  return $array === [] ? null : $array[array_key_last($array)];  
}

或者,polyfills/array-first-array-last 为 PHP 7.3 到 PHP 8.4 提供了 polyfills。

composer require polyfills/array-first-array-last

向后兼容性影响

已经声明自己的 array_firstarray_last 函数的现有 PHP 应用将会因为尝试重新声明这些函数将导致致命错误(Fatal error)。这些应用要么删除自己的声明,要么重命名函数,要么添加名称空间。

对于其他应用,此更改不会导致任何向后兼容性问题。

此外,可以对这些函数进行 polyfill。