Skip to content

array_get_first_element

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

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

Syntax

mixed array_get_first_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_first_element() when you do not want to modify the array, but rather just want the first element's value.

PHP gives us array_shift( $subjectArray ) to get the first element. However, array_shift() also removes the element from the array, shortening it by one.

Or you could iterate the array with a foreach or some other PHP construct. Using array_get_first_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.

Examples

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

$user = array(
	'user_id'   => 504,
	'name'      => 'Bob Jones',
	'social'    => array(
		'twitter' => '@bobjones',
		'website' => 'https://bobjones.com',
	),
	'languages' => array(
		'php'        => array(
			'procedural' => true,
			'oop'        => false,
		),
		'javascript' => true,
		'ruby'       => false,
	),
);

array_get_first_element( $user );
// Returns: 504

In this example, we have an array of arrays. When passing it into array_get_first_element, the first 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_first_element( $data ) );
/**
 * Returns:
 *      array(
 *			'user_id'    => 101,
 *			'name'       => 'Tonya',
 *			'email'      => 'tonya@foo.com',
 *			'has_access' => true,
 *		)
 */

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_first_element( $data, false );
// Returns: false

« Back to Array API

Clone this wiki locally