How to get the first item from an associative PHP array?

Php

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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];
}

Solution 3 - Php

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";

Solution 4 - Php

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);

Solution 5 - Php

another easy and simple way to do it use array_values

array_values($array)[0]

Solution 6 - Php

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.

Solution 7 - Php

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);
}

Solution 8 - Php

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

Instead of

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

As reset()

returns the first element of the array after reset;

Solution 9 - Php

You can make:

$values = array_values($array);
echo $values[0];

Solution 10 - Php

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));
?>

Solution 11 - Php

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

Solution 12 - Php

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)];

Solution 13 - Php

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;

Solution 14 - Php

You could use array_values

$firstValue = array_values($array)[0];

Solution 15 - Php

You could use array_shift

Solution 16 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - PhpsoulmergeView Answer on Stackoverflow
Solution 2 - PhpLSerniView Answer on Stackoverflow
Solution 3 - PhpJohn KugelmanView Answer on Stackoverflow
Solution 4 - PhpPaige RutenView Answer on Stackoverflow
Solution 5 - PhpBeginnerView Answer on Stackoverflow
Solution 6 - PhpcwallenpooleView Answer on Stackoverflow
Solution 7 - Phpw3bMak3rView Answer on Stackoverflow
Solution 8 - PhpSuryasish Dey View Answer on Stackoverflow
Solution 9 - Phpd0niekView Answer on Stackoverflow
Solution 10 - PhpWalkView Answer on Stackoverflow
Solution 11 - PhpWakar Ahmad KhanView Answer on Stackoverflow
Solution 12 - PhpcjcView Answer on Stackoverflow
Solution 13 - PhpS0SView Answer on Stackoverflow
Solution 14 - Phpevelikov92View Answer on Stackoverflow
Solution 15 - PhpCesarView Answer on Stackoverflow
Solution 16 - PhpDaantjeView Answer on Stackoverflow