Skip to content

array_get_last_element

Tonya Mork edited this page Mar 10, 2017 · 4 revisions

The array_get_last_element() function returns the value of the given array's last element. If the array is empty, then the default value is returned.

Syntax

mixed array_get_last_element( 
     array $subjectArray, 
     [ mixed $defaultValue = null ]
);

Where:

  • $subjectArray is the array that you want the function to work on

  • $defaultValue is optional. If given array is empty, then the default value is returned. You can pass what you want as the second argument, else null is used.

When to Use This Function

You will use array_get_last_element() when you do not want to modify the array, but rather just want the last element's value.

PHP gives you multiple ways to do this without using array_get_last_element():

  • array_pop( $subjectArray ) - however, it removes the element, thereby modifying the array
  • end( $subjectArray ) - however, it moves the array's pointer to the last element, which can cause you wonky behavior when using the array
  • or you could iterate the array with a foreach or some other PHP construct.

Using array_get_last_element() reduces your code and makes it more readable. The name of this function tells you what it does and what will happen when you invoke it. Plus, it does not change your array.

Examples

In this example, passing $user into the function will return false.

$user = array(
	'user_id'   => 504,
	'name'      => 'Bob Jones',
	'social'    => array(
		'twitter' => '@bobjones',
		'website' => 'https://bobjones.com',
	),
	'has_access' => false,
);

array_get_last_element( $user );
// Returns: false

In this example, we have an array of arrays. When passing it into array_get_last_element, the last element's array is returned, giving you the user's data.

$data = array(
	101 => array(
		'user_id'    => 101,
		'name'       => 'Tonya',
		'email'      => 'tonya@foo.com',
		'has_access' => true,
	),
	102 => array(
		'user_id'    => 102,
		'name'       => 'Sally',
		'email'      => 'sally@foo.com',
		'has_access' => false,
	),
	103 => array(
		'user_id'    => 103,
		'name'       => 'Rose',
		'has_access' => true,
	),
	104 => array(
		'user_id'    => 104,
		'name'       => 'Bob Jones',
		'has_access' => false,
	),
);

$user = array_get_last_element( $data ) );
/**
 * Returns:
 *      array(
 *			'user_id'    => 104,
 *			'name'       => 'Bob Jones',
 *			'has_access' => false,
 *		)
 */

If the value passed is an empty array, the default value is returned. If you do not specify a default value, then null is returned to you.

// $data is an empty array
$value = array_get_last_element( $data, false );
// Returns: false

« Back to Array API

Clone this wiki locally