array_last()WP 6.9.0

Gets the last element of the passed array.

Works for both regular and associative arrays: it takes the last element in the current array order, not the element with the largest numeric key.

PHP function polyfill array_last().

To get the last key of an array, use array_key_last().

No Hooks.

Returns

Mixed|null.

  • mixed — the last element of the array.
  • null — if the array is empty.

Usage

array_last( $array );
$array(array) (required)
The array from which you need to get the last element.

Examples

0

#1 Getting the last element of a normal array

$items = [ 'one', 'two', 'three' ];

$last_item = array_last( $items );

echo $last_item; // three
0

#2 Retrieving the last element of an associative array

$statuses = [
	'draft'   => 'Draft',
	'pending' => 'Pending review',
	'publish' => 'Published',
];

$last_status = array_last( $statuses );

echo $last_status; // Published
0

#3 Empty array

$items = [];

$last_item = array_last( $items );

var_dump( $last_item ); // null

Changelog

Since 6.9.0 Introduced.

array_last() code WP 7.0.2

function array_last( array $array ) { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.arrayFound
	if ( empty( $array ) ) {
		return null;
	}

	return $array[ array_key_last( $array ) ];
}