-
Notifications
You must be signed in to change notification settings - Fork 1
array_get_first_element
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.
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.
There are times when you don't want to modify the array, but rather just get the first element. array_get_first_element()
gives you means to do this. Your array is not changed.
mixed array_get_first_element(
array $subjectArray,
[ mixed $defaultValue = null ]
);
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