Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first element of an array

Tags:

arrays

php

I have an array:

array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )

I would like to get the first element of this array. Expected result: string apple

One requirement: it cannot be done with passing by reference, so array_shift is not a good solution.

How can I do this?

like image 926
hsz Avatar asked Dec 17 '09 12:12

hsz


People also ask

How do you find the first element of an array?

Alternativly, you can also use the reset() function to get the first element. The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

How do you properly access the first element in an array variable?

You can use find() to get the first element. var firstItem = yourArray.

What is the first index of array?

1-based indexing, 0-based indexing. Note: In most programming languages, the first array index is 0 or 1, and indexes continue through the natural numbers. The upper bound of an array is generally language and possibly system specific.


2 Answers

Original answer, but costly (O(n)):

array_shift(array_values($array));

In O(1):

array_pop(array_reverse($array));

Other use cases, etc...

If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use:

reset($array);

This should be theoretically more efficient, if a array "copy" is needed:

array_shift(array_slice($array, 0, 1));

With PHP 5.4+ (but might cause an index error if empty):

array_values($array)[0];
like image 138
blueyed Avatar answered Oct 10 '22 04:10

blueyed


As Mike pointed out (the easiest possible way):

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // Echoes "apple"

If you want to get the key: (execute it after reset)

echo key($arr); // Echoes "4"

From PHP's documentation:

mixed reset ( array | object &$array );

Description:

reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.

like image 860
lepe Avatar answered Oct 10 '22 06:10

lepe