224

If I had an array like:

$array['foo'] = 400;
$array['bar'] = 'xyz';

And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?

mickmackusa
49k13 gold badges96 silver badges163 bronze badges
asked Oct 24, 2009 at 6:21
2

16 Answers 16

380

reset() gives you the first value of the array if you have an element inside the array:

$value = reset($array);

It also gives you FALSE in case the array is empty.

Abhi Beckert
33.5k12 gold badges87 silver badges114 bronze badges
answered Oct 24, 2009 at 6:25
3
  • 1
    To note: $arr = array(/* stuff */); $val = $arr? reset($arr): /* value to indicate array is empty */; Commented Jun 6, 2014 at 19:08
  • More information on the reset function: www.w3schools.com/php/func_array_reset.asp Commented Dec 17, 2019 at 12:38
  • 6
    What if i want to get the key and value? Commented Jul 13, 2020 at 12:44
124

PHP latest

// Leveraging the ?? coalescing operator:
$el = $array[array_key_first($array)] ?? 'Array is empty';

Danger Will Robinson!

Emphasis mine:

And I wanted to get the first item out of that array without knowing the key for it

But what is the first item?

With lists it is obvious, it is item number 0:

 [ 'apple', 'banana', 'orange' ] // Apple it is.

[ 'a' => 'x', 'b' => 'y' ] is called an array in PHP, but is more aptly called a dictionary and has no "natural" order. So the code above (and the codes below) will return the "first" key in order of definition, but that order might change unintendedly, leading to subtle and difficult-to-track bugs:

// [ 'a' => 1, 'b' => 2 ]
// The first key is "a".
unset($arr['a']);
// [ 'b' => 2 ]
$arr['a'] = 1;
// [ 'b' => 2, 'a' => 1 ]
// The first key is now "b".

So, even if it might be a performance killer in some scenarios, you might perhaps be better served by

$arr[min(array_keys($arr))] ?? 'Array is empty';

or consider whether the "first key" is what you actually want.

PHP < 7.3

If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.

So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:

$value = empty($arr) ? $default : reset($arr);

The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:

$value = $default;
foreach(array_slice($arr, 0, 1) as $value);

Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:

foreach(array_slice($arr, 0, 1, true) as $key => $value);

To get the first item as a pair (key => value):

$item = array_slice($arr, 0, 1, true);

Simple modification to get the last item, key and value separately:

foreach(array_slice($arr, -1, 1, true) as $key => $value);

performance

If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:

$key = count($arr) ? array_keys($arr)[0] : null;

If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).

A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.

PHP 7.3+

PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.

So since PHP 7.3 the first value of $array may be accessed with

$array[array_key_first($array)];

You still had better check that the array is not empty though, or you will get an error:

$firstKey = array_key_first($array);
if (null === $firstKey) {
 $value = "Array is empty"; // An error should be handled here
} else {
 $value = $array[$firstKey];
}
answered Sep 27, 2017 at 9:09
6
  • @AhmedShefeer well, the other answer is not only the accepted one but has been there for eight more years. I'm sort of picking up the crumbs here :-D . But thanks for the vote of confidence! Commented Jun 26, 2018 at 16:07
  • 3
    It looks to me like this is the best answer, since the only other non-deprecated one that gives both the key and value is the aborted foreach loop, which is awkward. The other answers give only the value without the key. Commented Oct 24, 2018 at 0:15
  • 2
    loved this ans, modern approach and updated with time. Commented Jan 20, 2019 at 12:18
  • 1
    @LSerni Don't know if you are still active , but I was stuck and this well explained and updated post saved me. Thank you Commented Jun 3, 2019 at 7:33
  • @izk I'm always active! :-D Commented Jun 3, 2019 at 8:03
54

Fake loop that breaks on the first iteration:

$key = $value = NULL;
foreach ($array as $key => $value) {
 break;
}
echo "$key = $value\n";

Or use each() (warning: deprecated as of PHP 7.2.0):

reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
answered Oct 24, 2009 at 6:24
5
  • 2
    Probably because reset() is simpler. Commented Oct 24, 2009 at 23:40
  • 1
    Because the solution is in your first line of code but you're continuing writing another completely unneeded line. Commented Apr 30, 2011 at 11:54
  • 23
    reset wont return the key Commented Sep 17, 2013 at 13:22
  • 4
    +1 for the 'fake loop'. I've needed to retrieve the first elements key and value, while not going through each element. The reset() function would only retrieve the first value. Commented Dec 21, 2013 at 15:05
  • 3
    +1 for the fake loop as well, I need to kept the key so reset was not an option Commented Apr 12, 2014 at 17:39
33

There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.

$first = array_shift($array);

current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.

$first = current($array);

If you want to make sure that it is pointing to the first element, you can always use reset().

reset($array);
$first = current($array);
answered Oct 24, 2009 at 6:28
1
  • 3
    I like this answer as most complete, but note reset() actually returns the element, so following that with a $first = current($array) is redundant. Commented Jul 15, 2013 at 14:45
20

another easy and simple way to do it use array_values

array_values($array)[0]
answered Sep 27, 2016 at 7:31
2
  • reset() is a much better option since it returns false if the array is empty. your solution won't work for example in the question Commented Jun 20, 2017 at 21:15
  • 3
    In PHP 7+ something like this would work: array_values($array)[0] ?? FALSE Commented Feb 7, 2018 at 15:40
13

Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:

$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.

The way to do this without changing the pointer:

$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));

The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.

answered Jun 6, 2014 at 19:21
1
  • very descriptive answer, and it means a lot to others. Thanks man. Commented May 16, 2017 at 6:37
6

Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.

For Example:

if(is_array($array))
{
 reset($array);
 $first = key($array);
}
cwallenpoole
82.3k26 gold badges132 silver badges174 bronze badges
answered Jun 19, 2013 at 18:30
6

You could use array_values

$firstValue = array_values($array)[0];
answered Jan 24, 2022 at 10:15
5

We can do $first = reset($array);

Instead of

reset($array);
$first = current($array);

As reset()

returns the first element of the array after reset;

treyBake
6,5688 gold badges28 silver badges64 bronze badges
answered May 28, 2010 at 0:55
4

Use reset() function to get the first item out of that array without knowing the key for it like this.

$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);

output

400
mickmackusa
49k13 gold badges96 silver badges163 bronze badges
answered Mar 21, 2018 at 6:55
1
  • The advice to use reset() was given many years earlier on this page. Specifically the accepted answer from 2009! What new value does this answer provide? Commented May 7, 2024 at 4:09
3

You can make:

$values = array_values($array);
echo $values[0];
answered Jun 30, 2017 at 12:55
2

Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:

$first = $array[array_key_first($array)];

More likely, you'll want to handle the case where the array is empty:

$first = (empty($array)) ? $default : $array[array_key_first($array)];
answered Oct 10, 2018 at 14:32
2

You can try this.

To get first value of the array :-

<?php
 $large_array = array('foo' => 'bar', 'hello' => 'world');
 var_dump(current($large_array));
?>

To get the first key of the array

<?php
 $large_array = array('foo' => 'bar', 'hello' => 'world');
 $large_array_keys = array_keys($large_array);
 var_dump(array_shift($large_array_keys));
?>
Dave
3,0917 gold badges22 silver badges33 bronze badges
answered Feb 6, 2017 at 11:45
2

In one line:

$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];

Expanded:

$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
answered Jun 9, 2021 at 15:54
1

You could use array_shift

answered Oct 24, 2009 at 6:31
1
  • 7
    But be aware the array will have one item removed. Commented Sep 26, 2016 at 14:26
1

I do this to get the first and last value. This works with more values too.

$a = array(
 'foo' => 400,
 'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz
answered Jun 17, 2014 at 9:49
1
  • 1
    This only works when the internal pointer is at the first element. While this is good because it doesn't reset the position of the pointer, it only works when the pointer is already rest. Commented Oct 10, 2018 at 14:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.