1358

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?

mickmackusa
49k13 gold badges96 silver badges163 bronze badges
asked Dec 17, 2009 at 12:26
6
  • 2
    What do you mean, can't be done by reference? Commented Dec 17, 2009 at 12:34
  • Function should not works using &$array as params. Commented Dec 17, 2009 at 12:41
  • 4
    I suspect that what you "really" mean by "can't be done by reference", is that your array is being returned dynamically from a database, and you don't want to pass the array into a variable before taking the first element from it. If I'm right, then the vast majority of all the solutions provided to you below (including the accepted answer), are insufficient. Commented Oct 23, 2012 at 20:16
  • 1
    Do you just have to get it or get it and remove it from the existing array? Commented Jul 10, 2014 at 15:21
  • For basic use of Arrays you can review this link technofusions.com/introduction-to-arrays-in-php Commented Jul 28, 2016 at 18:50

37 Answers 37

1
2
1687
Answer recommended by PHP Collective

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];
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Sep 22, 2010 at 16:04
33
  • 87
    +1 for the clever workaround to prevent modifying the original array with array_values() Commented Sep 14, 2011 at 12:05
  • 56
    I get this: <b>Strict Standards</b>: Only variables should be passed by reference. Nice workaround btw Commented Mar 21, 2012 at 13:55
  • 210
    Isn't this a little overkill? What if the array contains several thousands of elements? Is it justified to create a whole new array just to get its first element? list() and reset() are much nicer solutions to my opinion. Commented Jun 12, 2012 at 11:25
  • 40
    I agree. Total overkill and extraordinary resource heavy compared to one line which resets and returns the current value: reset($array); Commented Sep 13, 2012 at 18:42
  • 51
    -1 As the above commenters have said. It's baffling to me that this has 101 upvotes. Commented Oct 8, 2012 at 10:47
915

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.

answered Nov 15, 2011 at 3:33
10
  • 19
    The array's iterator is modified. If you do this in a foreach with the subject array, you'll screw it up. Commented Nov 13, 2013 at 6:11
  • 2
    @Zenexer this is not always (usually) true. Usually in practise, foreach will copy the array which is it looping through. Commented Jun 6, 2015 at 11:32
  • 1
    @Angger after reset, you can call key($arr) and you will get '4' (added into answer) Commented Apr 19, 2017 at 3:03
  • 9
    Neither @Zenexer nor Luke Cousins are right: 1) foreach does not use internat pointer of an array - instead it creates it's own pointer. It is easy to check calling reset inside foreach - the loop will follow it's way with no effect from reset(). 2) No, foreach DOES NOT create a copy of an array!!! It only creates it's own pointer (not even a copy of an existing one - it is also easy to check, calling next() before foreach). Commented Jun 1, 2018 at 8:01
  • 1
    @Zenexer Well, you don't have to take my word :) It is pretty well describet in this post: stackoverflow.com/a/14854568/2828391 Commented Jun 4, 2018 at 12:59
322
$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Jun 8, 2012 at 6:01
6
  • 2
    I haven't actually tested it, but it seems this approach would be the most efficient. Commented Aug 27, 2012 at 15:23
  • 4
    Only problem is the question asked for the value, not the key. Thus current($array) should be used instead of of key($array) Commented Sep 13, 2012 at 18:40
  • 4
    @zmonteca $first_value = reset($array); here you get the value, reset() function rewinds arrays internal pointer and returns first element. Commented Oct 3, 2012 at 13:16
  • 2
    the best answer! was looking for key() equivalence to get the first value. This helps! Commented Oct 19, 2012 at 10:06
  • 2
    What if the array is empty? reset() will return false, which may lead to bugs if you expect the array to contain bool values. Commented Oct 26, 2021 at 19:02
176

current($array)

returns the first element of an array, according to the PHP manual.

Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

So it works until you have re-positioned the array pointer, and otherwise you'll have to use reset() which ll rewind array and ll return first element of array

According to the PHP manual reset.

reset() rewinds array's internal pointer to the first element and returns the value of the first array element.

Examples of current() and reset()

$array = array('step one', 'step two', 'step three', 'step four');
// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"
//Forward the array pointer and then reset it
// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"
// reset pointer, start again on step one
echo reset($array) . "<br />\n"; // "step one"
answered Sep 12, 2014 at 8:07
5
  • 35
    current($array) will only work if the array pointer is "currently" pointing to the first element, otherwise reset($array) would be required. Commented Jan 15, 2015 at 23:23
  • 7
    It seems current() no longer requires a reference, although the PHP docs do not reflect this. So I think this has become the best solution. Commented Feb 18, 2016 at 0:31
  • @Ryan agreed, but this solution was given 2 years prior to 2014 in this other answer of this same thread... Weird that this incomplete sentence got more upvotes. Commented Jul 4, 2018 at 13:23
  • What if the array is empty? reset() and current() will return false, which may lead to bugs if you expect the array to contain bool values. Commented Oct 26, 2021 at 19:03
  • 1
    Different horses for courses. reset() if you have an array variable. current() when nesting functions e.g. current(array_column([],'key')) Commented Aug 2, 2023 at 15:06
116
$arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'

If you don't want to lose the current pointer position, just create an alias for the array.

Martin
16.5k1 gold badge33 silver badges51 bronze badges
answered Dec 17, 2009 at 12:31
4
  • 1
    didn't get it, what do you mean? It works fine whether the key of the first is bigger than the other ones. Commented Dec 17, 2009 at 12:38
  • 30
    +1 FYI reset() already returns the first element, so there is no need to use current() -- echo reset($arr) should suffice Commented Sep 21, 2011 at 14:58
  • @Mike but you might prefer current to reset to avoid PHP notice/error produced in reference cases, e.g. current(array_filter(...)); in 3v4l. Commented Jul 5, 2018 at 11:07
  • 1
    What if the array is empty? reset() will return false, which may lead to bugs if you expect the array to contain bool values. Commented Oct 26, 2021 at 19:04
105

PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:

Apart from being semantically meaningful, these functions don't even move the array pointer (as foreach would do).

Having the keys, one can get the values by the keys directly.


Examples (all of them require PHP 7.3+)

Getting the first/last key and value:

$my_array = ['IT', 'rules', 'the', 'world'];
$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];
$last_key = array_key_last($my_array);
$last_value = $my_array[$last_key];

Getting the first/last value as one-liners, assuming the array cannot be empty:

$first_value = $my_array[ array_key_first($my_array) ];
$last_value = $my_array[ array_key_last($my_array) ];

Getting the first/last value as one-liners, with defaults for empty arrays:

$first_value = empty($my_array) ? 'default' : $my_array[ array_key_first($my_array) ];
$last_value = empty($my_array) ? 'default' : $my_array[ array_key_last($my_array) ];
answered Sep 13, 2018 at 17:45
3
76

You can get the Nth element with a language construct, "list":

// First item
list($firstItem) = $yourArray;
// First item from an array that is returned from a function
list($firstItem) = functionThatReturnsArray();
// Second item
list( , $secondItem) = $yourArray;

With the array_keys function you can do the same for keys:

list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Apr 12, 2012 at 13:40
8
  • 2
    This is exactly what I do: list($first_value) = $my_array; In my opinion, the very best option. It does not have the issues from the other answers presented here: no "overkill" because it does not copy or the array or create a new one. No "references": the array is not modified. No "reset": no changes to the array internal pointer... Commented Aug 30, 2012 at 12:44
  • 7
    Very elegant solution, but throws an E_NOTICE when the array is empty. Commented Jan 11, 2013 at 17:22
  • 17
    Isn't this wrong?! It works only if array keys are int, try doing list($firstItem) = array('key1' => 'value1'); and you will get an error Notice: Undefined offset: 0 Commented Mar 5, 2013 at 14:05
  • 2
    @Sergiy but then you loose the biggest advantage of this solution, and that's not copying the entire original array to another needlessly. Still, +1 for the benefits assuming you can guarantee an integer indexed array Commented Mar 26, 2013 at 19:09
  • 12
    To clarify: list($x) = foo(); is equivalent to $x = foo()[0];. Note that this is not necessarily the same as "get the first item", since even an integer-indexed array may not have an element with key 0. In my case I was doing "list($order) = get_order($user);" but "get_order" was returning orders keyed by their ID, which was usually not 0. As @Sergiy says, array_values() fixes this, but detracts from the efficiency and (more importantly) readability of the code. Commented Aug 2, 2013 at 9:28
56

PHP 5.4+:

array_values($array)[0];
hsz
153k63 gold badges267 silver badges320 bronze badges
answered Apr 23, 2013 at 14:50
2
  • PHP 4: $array_values = array_values($array); $value = $array_values[0]; Commented Nov 9, 2016 at 11:41
  • if the array is empty it will return undefined key 0 so use it with caution Commented Jun 17, 2020 at 11:03
31

Some arrays don't work with functions like list, reset or current. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.

If you want to pull the first value regardless of the array, you can short-circuit an iterator:

foreach($array_with_unknown_keys as $value) break;

Your value will then be available in $value and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).

You can grab the key this way too:

foreach($array_with_unknown_keys as $key=>$value) break;

If you're calling this from a function, simply return early:

function grab_first($arr) {
 foreach($arr as $value) return $value;
}
answered Jul 22, 2012 at 20:41
1
  • I suppose this is one of the fastest ways because using the language construct foreach rather than a function call (which is more expensive). designcise.com/web/tutorial/… Commented Sep 29, 2017 at 7:56
28

Suppose:

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

Just use:

$array[key($array)]

to get first element or

key($array)

to get first key.

Or you can unlink the first if you want to remove it.

hsz
153k63 gold badges267 silver badges320 bronze badges
answered Aug 9, 2012 at 12:23
1
  • 10
    Wht not simply use current then? Commented Mar 5, 2013 at 14:02
22

From Laravel's helpers:

function head($array)
{
 return reset($array);
}

The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, and it doesn't touch the original array (note it returns false if the array is empty).

Usage example:

$data = ['foo', 'bar', 'baz'];
current($data); // foo
next($data); // bar
head($data); // foo
next($data); // baz

Also, here is an alternative. It's very marginally faster, but more interesting. It lets easily change the default value if the array is empty:

function head($array, $default = null)
{
 foreach ($array as $item) {
 return $item;
 }
 return $default;
}

For the record, here is another answer of mine, for the array's last element.

Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered May 3, 2017 at 0:45
0
14

Simply do:

array_shift(array_slice($array,0,1));
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Dec 15, 2012 at 10:38
1
  • It is an unattractive (and unexplained) technique since there are single-call techniques to achieve the same thing. Commented Dec 17, 2020 at 6:02
14
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;

Output:

apple
Pang
10.2k146 gold badges87 silver badges126 bronze badges
answered Jun 16, 2012 at 21:05
13

PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:

There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:

<?php
if (!function_exists('array_key_first')) {
 function array_key_first($arr) {
 foreach($arr as $key => $unused) {
 return $key;
 }
 return NULL;
 }
}
?>

Source

This polyfill can then be used in this next one:

if (!function_exists('array_key_last')) {
 function array_key_last($arr) {
 return array_key_first(array_reverse($arr, true));
 }
}
miken32
42.6k16 gold badges127 silver badges176 bronze badges
answered Mar 13, 2020 at 14:10
1
  • @DouglasVicentini it is not guaranteed that checking if one function exists will be sufficient to determine if both functions have been declared. It is possible that one of the functions has been declared in userland (independent of the PHP version). If you want a single check based on the PHP version, do that explicitly. Commented May 23 at 14:48
12

I would do echo current($array) .

answered Aug 9, 2012 at 12:40
6
  • 1
    @hsz Doesn't matter, current() doesn't error when non-references are passed. Provided that the pointer is still at the beginning this works. Commented Jul 12, 2013 at 16:54
  • but it produces a Notice which makes your logs dirty and well... you should get rid of Notices also wven if they are not critical Commented Apr 24, 2015 at 15:20
  • 1
    @dmikam no it does not. Actually reset produces the "Only variables should be passed by reference" notice while current does not: Online PHP Editor example of current(array_filter(...));. Commented Jul 4, 2018 at 13:35
  • @CPHPython, seems like you are right... looks like I had this idea of current from old times of PHP 4 where it really produces Fatal error: sandbox.onlinephpfunctions.com/code/… The only issue I see in using current is that it does not guarantee that the returned element is the first element of an array (internal pointer may be modified by the called function). Virtually it may return random element of an array. Commented Jul 5, 2018 at 10:10
  • 1
    @CPHPython A bit artificial example, but it demonstrates well my thoughts: sandbox.onlinephpfunctions.com/code/… just imagine that you receive your array from some function that uses next(), end() or any other function that modifies array's internal pointer. In my example, current() returns null because the internal pointer is "out of range" of array. But it may 'virtually' point to any/random element too. Commented Jul 10, 2018 at 10:19
9
$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);
// The first element of your array is:
echo $myArray[$arrayKeys[0]];
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Aug 12, 2014 at 19:48
0
8
$array=array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$firstValue = each($array)[1];

This is much more efficient than array_values() because the each() function does not copy the entire array.

For more info see http://www.php.net/manual/en/function.each.php

answered May 17, 2013 at 16:35
3
  • because the each() function does not copy the entire array. +1 Commented Aug 4, 2013 at 0:18
  • 2
    But the thing is that you should do a reset before, if the internal pointer is not at the beginning you are not going to get the first element. Commented Jul 22, 2014 at 15:59
  • But each() receives an array by reference and the requirement of the initial questions is not to do so Commented Apr 24, 2015 at 15:17
8

A kludgy way is:

$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
function get_first ($foo) {
 foreach ($foo as $k=>$v){
 return $v;
 }
}
print get_first($foo);
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Dec 17, 2009 at 13:08
2
  • 3
    At least you're honest - it's kludgy! But, it works, and I've used it in the past until learning the list() technique above. Commented Mar 21, 2013 at 15:23
  • 1
    If you are doing this, you might as well use reset() as the array pointer is reset before foreachis called anyway. Commented Oct 21, 2014 at 16:34
6

Use:

$first = array_slice($array, 0, 1); 
$val= $first[0];

By default, array_slice does not preserve keys, so we can safely use zero as the index.

Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Apr 5, 2012 at 10:41
6

Most of these work! BUT for a quick single line (low resource) call:

$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $array[key($array)];
// key($array) -> will return the first key (which is 4 in this example)

Although this works, and decently well, please also see my additional answer: https://stackoverflow.com/a/48410351/1804013

answered Nov 5, 2013 at 20:41
3
  • 5
    This is equivalent to using current($array), which requires that the array's internal pointer be at the first element anyway, in which case, echo reset($array) is most appropriate. Commented Oct 21, 2014 at 16:35
  • @Tyzoid he actually wrote another answer here with your suggestion, but he omitted your explanation... Thank you. Commented Jul 4, 2018 at 11:38
  • @Tyzoid: I made an additional answer/update awhile go: stackoverflow.com/a/48410351/1804013 Commented Sep 14, 2018 at 8:22
4

I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get 'apple'.

answered Dec 17, 2009 at 13:23
4

This is a little late to the game, but I was presented with a problem where my array contained array elements as children inside it, and thus I couldn't just get a string representation of the first array element. By using PHP's current() function, I managed this:

<?php
 $original = array(4 => array('one', 'two'), 7 => array('three', 'four'));
 reset($original); // to reset the internal array pointer...
 $first_element = current($original); // get the current element...
?>

Thanks to all the current solutions helped me get to this answer, I hope this helps someone sometime!

answered Apr 20, 2013 at 11:48
0
4

From PHP8.5, array_first() is available as a pointer-ignorant native function to access the first value in an array. Demo

$array = [
 4 => 'apple',
 7 => 'orange',
 13 => 'plum'
];
var_export(
 array_first($array)
);
// 'apple'

This new function was unanimously supported along with array_last().

If the input array is empty, this function returns null (which might also be the value of a non-empty array).

Resources

The polyfill:

function array_first(array $array): mixed { 
 return $array === [] ? null : $array[array_key_first($array)]; 
}
answered May 16 at 17:38
0
3

Two solutions for you.

Solution 1 - Just use the key. You have not said that you can not use it. :)

<?php
 // Get the first element of this array.
 $array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
 // Gets the first element by key
 $result = $array[4];
 // Expected result: string apple
 assert('$result === "apple" /* Expected result: string apple. */');
?>

Solution 2 - array_flip() + key()

<?php
 // Get first element of this array. Expected result: string apple
 $array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
 // Turn values to keys
 $array = array_flip($array);
 // You might thrown a reset in just to make sure
 // that the array pointer is at the first element.
 // Also, reset returns the first element.
 // reset($myArray);
 // Return the first key
 $firstKey = key($array);
 assert('$firstKey === "apple" /* Expected result: string apple. */');
?>

Solution 3 - array_keys()

echo $array[array_keys($array)[0]];
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Jul 7, 2012 at 9:18
2

No one has suggested using the ArrayIterator class:

$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'

gets around the by reference stipulation of the OP.

answered Oct 23, 2018 at 0:39
1
  • This should be the correct answer. Also works to get the first key: (new ArrayIterator($array))->key(). Note that it correctly returns null for both value and key when the array is empty (rather than returning a pseudo-value like false). Unfortunately doesn't work for Laravel's Collection class though, it always returns null Commented May 22, 2021 at 21:51
2

I imagine the author just was looking for a way to get the first element of an array after getting it from some function (mysql_fetch_row, for example) without generating a STRICT "Only variables should be passed by reference".

If it so, almost all the ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:

$first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
// or
$first_item_of_array = reset($tmp_arr = func_get_my_huge_array());

This way you don't get the STRICT message on screen, nor in logs, and you don't create any additional arrays. It works with both indexed AND associative arrays.

Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Apr 27, 2015 at 8:50
2

One line closure, copy, reset:

<?php
$fruits = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
echo (function() use ($fruits) { return reset($fruits); })();

Output:

apple

Alternatively the shorter short arrow function:

echo (fn() => reset($fruits))();

This uses by-value variable binding as above. Both will not mutate the original pointer.

answered Mar 20, 2020 at 22:55
2
  • Note $copy = $fruits; echo reset($copy); is far more portable accross Php versions. Commented Mar 20, 2020 at 23:24
  • If you don't care about the original pointer. reset($fruits) will do! Commented Mar 20, 2020 at 23:33
1

Use array_keys() to access the keys of your associative array as a numerical indexed array, which is then again can be used as key for the array.

When the solution is arr[0]:

(Note, that since the array with the keys is 0-based index, the 1st element is index 0)

You can use a variable and then subtract one, to get your logic, that 1 => 'apple'.

$i = 1;
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[$i-1]];

Output:

apple

Well, for simplicity- just use:

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[0]];

Output:

apple

By the first method not just the first element, but can treat an associative array like an indexed array.

answered Jun 11, 2015 at 5:26
0

I like the "list" example, but "list" only works on the left-hand-side of an assignment. If we don't want to assign a variable, we would be forced to make up a temporary name, which at best pollutes our scope and at worst overwrites an existing value:

list($x) = some_array();
var_dump($x);

The above will overwrite any existing value of $x, and the $x variable will hang around as long as this scope is active (the end of this function/method, or forever if we're in the top-level). This can be worked around using call_user_func and an anonymous function, but it's clunky:

var_dump(call_user_func(function($arr) { list($x) = $arr; return $x; },
 some_array()));

If we use anonymous functions like this, we can actually get away with reset and array_shift, even though they use pass-by-reference. This is because calling a function will bind its arguments, and these arguments can be passed by reference:

var_dump(call_user_func(function($arr) { return reset($arr); },
 array_values(some_array())));

However, this is actually overkill, since call_user_func will perform this temporary assignment internally. This lets us treat pass-by-reference functions as if they were pass-by-value, without any warnings or errors:

var_dump(call_user_func('reset', array_values(some_array())));
answered Jul 12, 2013 at 16:32
0

A small change to what Sarfraz posted is:

$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 0, 1);
print_r ($output);
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered May 23, 2011 at 6:46
0
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.