1311

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
  • 43,625
  • 12
  • 83
  • 136
hsz
  • 148,279
  • 62
  • 259
  • 315
  • 1
    What do you mean, can't be done by reference? – cjk Dec 17 '09 at 12:34
  • Function should not works using `&$array` as params. – hsz Dec 17 '09 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. – cartbeforehorse Oct 23 '12 at 20:16
  • 1
    Do you just have to get it or get it and remove it from the existing array? – Jo Smo Jul 10 '14 at 15:21
  • For basic use of Arrays you can review this link http://www.technofusions.com/introduction-to-arrays-in-php/ – Vikrant Vir Bhalla Jul 28 '16 at 18:50
  • It sounds like he doesn't want the array modified because it is passed by reference. – CommandZ Oct 04 '20 at 13:56
  • @ray we do not need to add "PHP" to the title of every PHP question -- that is what [tag:php] tags are for. – mickmackusa Feb 03 '23 at 04:09
  • @mickmackusa sorry first if I am misunderstanding something. But the title of the question is too generic that it shows up in the related section of some other unrelated technology like [this](https://stackoverflow.com/questions/29818179/mongodb-find-all-matched-array-element-from-single-document). (even before I comment the link here). That's why I thought it would do no harm to make this question more specific in the title. – ray Feb 03 '23 at 13:19
  • @ray the Related list is often horrible for PHP pages. The Linked list contains this page because there is a hyperlink on this page that connects to that page. – mickmackusa Feb 03 '23 at 20:49

39 Answers39

1635

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
  • 30,738
  • 21
  • 105
  • 131
blueyed
  • 27,102
  • 4
  • 75
  • 71
  • 86
    +1 for the clever workaround to prevent modifying the original array with array_values() – ChrisR Sep 14 '11 at 12:05
  • 53
    I get this: Strict Standards: Only variables should be passed by reference. Nice workaround btw – Simone Mar 21 '12 at 13:55
  • 207
    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. – Martin Dimitrov Jun 12 '12 at 11:25
  • 1
    +1 because this works event with array_keys if I need the first key – albanx Jun 19 '12 at 08:52
  • yes, overkill workaround, just the reset PHP built-in function, as mentionned after. – Yoong Kim Jul 16 '12 at 04:21
  • 40
    I agree. Total overkill and extraordinary resource heavy compared to one line which resets and returns the current value: reset($array); – zmonteca Sep 13 '12 at 18:42
  • 51
    -1 As the above commenters have said. It's baffling to me that this has 101 upvotes. – Lightness Races in Orbit Oct 08 '12 at 10:47
  • 2
    This answer is even more incorrect, if the assumption I make in my comment to the original question is correct. – cartbeforehorse Oct 23 '12 at 20:17
  • 6
    array_shift(array_slice($array,0,1)) // <-- in theory faster as it considers only the first element – E Ciotti Nov 08 '12 at 01:50
  • 3
    First of all it doesn't run with Strict Standards as said before. Using reset() (and key() after it, if necessary) is a much more graceful and performant option. – Ain Tohvri Nov 29 '12 at 13:59
  • 3
    The reset(&$arr) post below is far more efficient. – eli Dec 03 '12 at 21:49
  • 1
    There's a fine line between avoiding premature optimization and senseless resource waste. – Septagram Feb 20 '13 at 09:30
  • 5
    THIS WRONG! USE echo reset($arr); – Ivan Apr 12 '13 at 10:45
  • @albanx If you want the key use the accepted answer [here](http://stackoverflow.com/questions/1028668/get-first-key-in-a-possibly-associative-array). – Joel Mellon Aug 29 '13 at 22:31
  • 4
    +1 for array_values solution as it does not modify the original array – Vladimir Hraban Jan 24 '14 at 18:02
  • 1
    I am completely flabbergasted by the fact that in 2014 we can't get better than a reset function that cannot be used with passed by reference value. PHP should really consider separating array into lists and dictionnaries. – fe_lix_ Jun 18 '14 at 13:23
  • 3
    there is an offset problem with `array_values($arr)[0]` in case the input array `$arr` is empty. – ulkas Aug 19 '14 at 11:05
  • All I needed was array_slice. The other stuff was unnecessary for me. Thanks! – ReynekeVosz Dec 01 '14 at 11:08
  • 1
    the correct and simplest answer is the one below, e.g: current($arr); – Ludo - Off the record Jan 05 '15 at 13:12
  • This is where community based moderation should come into play. The selected answer does this the wrong way, yet receives hundreds of upvotes anyway. The best answer is one posted by user `lepe` below. – a coder Sep 04 '15 at 16:15
  • @acoder not sure what you mean: my/this answer covers different use cases, including the one using `reset`?! – blueyed Sep 08 '15 at 12:10
  • 2
    I don't understand everybody complaining about this answer. `reset` CHANGES the array by reseting its internal pointer, so if you use `reset` method within a loop using internal array's pointer, then it'll mess-up the expected loop behavior and could make it run forever. As said by the author, if you do not care about the pointer, then `reset` is the way to go, else it is definitely not an option – Huafu Jan 25 '16 at 05:19
  • 1
    The problem here is that array_shift is expensive on large arrays. It is better to use `array_pop(array_reverse($array))`. Also, the OP just says that they want the first value, not to loop through them all, so the cost of `array_shift` provides no benefit. – caponica Feb 26 '16 at 14:46
  • See [my answer](http://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array/43749334#43749334) for the ultimate solution. Feel free to integrate it in this answer. – Gras Double May 03 '17 at 00:50
  • 3
    I cannot understand how `array_reverse($array)` could be O(1). – ntd Sep 28 '17 at 15:09
  • @blueyed how is possible for array_reverse to be O(1)?, it creates a new array, it forces the function to be at least O(n). – lcjury Jan 09 '18 at 19:50
  • As @ntd said, I think is not O(1). If you take a look in the implementation, you can see a loop in both case of the `if`: https://github.com/php/php-src/blob/5a31e14beba625f1b32d61d6aec85b3df7f023cc/ext/standard/array.c#L4248 – Erusso87 May 03 '18 at 11:28
  • array_shift = O(n), array_pop = O(1), array_values = O(n), array_reverse = O(n). Then: array_shift(array_values()) = O(n + n) = O(n), array_pop(array_reverse()) = O(1 + n) = O(n) – Bolebor Sep 19 '19 at 09:27
  • starting from PHP8 this construction is a bug: $array[0] Keys can be negative, so you never know if first element is not $array[-30] – Eugene Kaurov Nov 14 '19 at 10:18
  • 3
    From PHP 7.3 you can use `array_key_first` https://www.php.net/manual/en/function.array-key-first.php – Manic Depression Mar 11 '20 at 06:57
  • 1
    with php 7.3.2 your `array_pop(array_reverse($array))` throws **only variables can be passed by reference** – Muhammad Omer Aslam Jan 03 '21 at 23:25
  • 1
    1531 upvotes? A perfect demonstration on why democracy fails – Jack Dec 10 '21 at 21:04
  • array_pop() pops the last element of array If you use php 8 array_pop pops by referenced array So it accepts varable. You can store the reversed array in a variable then array_pop the reversed array. – mahmood Jun 27 '22 at 12:47
892

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.

Tom
  • 1,223
  • 1
  • 16
  • 27
lepe
  • 24,677
  • 9
  • 99
  • 108
  • Although it is passed by reference to reset, the original array is not modified. I'm guessing that's the reason hsz does not want to pass it by reference..? – Dennis Jamin Oct 04 '13 at 11:22
  • 17
    The array's iterator is modified. If you do this in a `foreach` with the subject array, you'll screw it up. – Zenexer Nov 13 '13 at 06:11
  • 2
    @Zenexer this is not always (usually) true. Usually in practise, `foreach` will copy the array which is it looping through. – Luke Cousins Jun 06 '15 at 11:32
  • what if I want to get the '4' (assign name) values? – Angger Apr 18 '17 at 12:31
  • 1
    @Angger after reset, you can call `key($arr)` and you will get '4' (added into answer) – lepe Apr 19 '17 at 03: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). – dmikam Jun 01 '18 at 08:01
  • @dmikam Years later, I realize that’s definitely a possibility, though I haven’t tested it. I’ll take your word for it. – Zenexer Jun 01 '18 at 09:29
  • 1
    @Zenexer Well, you don't have to take my word :) It is pretty well describet in this post: https://stackoverflow.com/a/14854568/2828391 – dmikam Jun 04 '18 at 12:59
  • What if the array is empty? `reset()` will return `false`, which may lead to bugs if you expect the array to contain `bool` values. – Jacob Oct 26 '21 at 19:01
  • @Jacob In such cases, you would check if an array is empty before calling this function. – lepe Oct 27 '21 at 00:51
317
$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ijas Ameenudeen
  • 9,069
  • 3
  • 41
  • 54
  • 2
    I haven't actually tested it, but it seems this approach would be the most efficient. – mason81 Aug 27 '12 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) – zmonteca Sep 13 '12 at 18:40
  • 4
    @zmonteca $first_value = reset($array); here you get the value, reset() function rewinds arrays internal pointer and returns first element. – S3Mi Oct 03 '12 at 13:16
  • 2
    the best answer! was looking for key() equivalence to get the first value. This helps! – Alain Tiemblo Oct 19 '12 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. – Jacob Oct 26 '21 at 19:02
156

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"
Tofeeq
  • 2,523
  • 1
  • 23
  • 20
  • 7
    I don't know why this wasn't the accepted answer, as it answers the question fairly simply and accurately. – relipse Dec 30 '14 at 21:31
  • 30
    ```current($array)``` will only work if the array pointer is "currently" pointing to the first element, otherwise ```reset($array)``` would be required. – Jon Jan 15 '15 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. – Ryan Feb 18 '16 at 00:31
  • @Ryan agreed, but this solution was given 2 years prior to 2014 in [this other answer of this same thread](https://stackoverflow.com/a/11883690/6225838)... Weird that this incomplete sentence got more upvotes. – CPHPython Jul 04 '18 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. – Jacob Oct 26 '21 at 19:03
  • Different horses for courses. `reset()` if you have an array variable. `current()` when nesting functions e.g. `current(array_column([],'key'))` – Jono Aug 02 '23 at 15:06
115
$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,093
  • 1
  • 29
  • 48
yoda
  • 10,834
  • 19
  • 64
  • 92
  • 1
    didn't get it, what do you mean? It works fine whether the key of the first is bigger than the other ones. – yoda Dec 17 '09 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 – Mike Sep 21 '11 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](https://3v4l.org/sUrcB). – CPHPython Jul 05 '18 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. – Jacob Oct 26 '21 at 19:04
89

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) ];
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
  • 4
    Shorten with [null-coalescing operator](https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op), usually null is default so: `$first_value = $my_array[array_key_first($my_array)] ?? null;` – Mitchell McKenna Apr 01 '20 at 16:37
  • 2
    From PHP 7.3, this should be the selected answer. – Xavi Montero Oct 03 '21 at 10:20
  • They should add `array_first` too. To get first item. And possibly `array_second` ;) – PeterM Jun 20 '23 at 14:41
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
  • 30,738
  • 21
  • 105
  • 131
Sergiy Sokolenko
  • 5,967
  • 35
  • 37
  • 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... – J. Bruni Aug 30 '12 at 12:44
  • 7
    Very elegant solution, but throws an E_NOTICE when the array is empty. – Tgr Jan 11 '13 at 17:22
  • @Tgr that can be easily overcome by checking if `count($array) > 0`. – Mike Feb 23 '13 at 23:03
  • 1
    @Mike yes, but then it is not so elegant anymore :) – Tgr Feb 24 '13 at 23:36
  • 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` – Marco Demaio Mar 05 '13 at 14:05
  • @MarcoDemaio, you're correct, but you can always use array_values() function in such cases: list($firstItem) = array_values($yourArray); – Sergiy Sokolenko Mar 05 '13 at 16:25
  • 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 – Jeff Lambert Mar 26 '13 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. – Warbo Aug 02 '13 at 09:28
56

PHP 5.4+:

array_values($array)[0];
hsz
  • 148,279
  • 62
  • 259
  • 315
Samer Ata
  • 1,027
  • 1
  • 12
  • 11
28

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;
}
Lee Benson
  • 11,185
  • 6
  • 43
  • 57
  • I suppose this is one of the fastest ways because using the language construct foreach rather than a function call (which is more expensive). http://www.designcise.com/web/tutorial/how-to-get-the-first-element-of-an-array-in-php – Ildar Amankulov Sep 29 '17 at 07: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
  • 148,279
  • 62
  • 259
  • 315
Lucas
  • 293
  • 3
  • 3
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
  • 30,738
  • 21
  • 105
  • 131
Gras Double
  • 15,901
  • 8
  • 56
  • 54
18

Keep this simple! There are lots of correct answers here, but to minimize all the confusion, these two work and reduce a lot of overhead:

key($array) gets the first key of an array
current($array) gets the first value of an array


EDIT:
Regarding the comments below. The following example will output: string(13) "PHP code test"

$array = array
(
   '1'           => 'PHP code test',  
   'foo'         => 'bar', 5 , 5 => 89009, 
   'case'        => 'Random Stuff: '.rand(100,999),
   'PHP Version' => phpversion(),
   0             => 'ending text here'
);

var_dump(current($array));
tfont
  • 10,891
  • 7
  • 56
  • 52
  • 15
    Uhh. `current` equals current element. You have to reset the pointer to the beginning of the array to ensure it is actually at the beginning. – waterloomatt Jun 26 '18 at 12:29
  • 2
    current () will get the current element, not the first element. It's different. – amir22 May 05 '19 at 17:07
  • current will work if there is only one element in the array. – Zameer Fouzan Sep 24 '19 at 13:27
  • @tfont, what happens if you add the line `next($array);` immediately before the `var_dump` line? I'm pretty sure you'll get `string(3) "bar"` and that's not "the first value of an array". – Pedro Amaral Couto Dec 20 '22 at 00:05
14

Simply do:

array_shift(array_slice($array,0,1));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
  • It is an unattractive (and unexplained) technique since there are single-call techniques to achieve the same thing. – mickmackusa Dec 17 '20 at 06:02
13
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;

Output:

apple
Pang
  • 9,564
  • 146
  • 81
  • 122
tekin
  • 147
  • 1
  • 2
13

I would do echo current($array) .

user1485518
  • 233
  • 3
  • 11
  • 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. – Dan Lugg Jul 12 '13 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 – dmikam Apr 24 '15 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(...));`](https://3v4l.org/sUrcB). – CPHPython Jul 04 '18 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: http://sandbox.onlinephpfunctions.com/code/5efb3f322b15cbb3938c2729d6de97f7d73bc90c 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. – dmikam Jul 05 '18 at 10:10
  • @dmikam I was never able to return a random element of an array with `current`... Here's an [3v4l example](https://3v4l.org/B38nJ) that adds an element, sorts the array and removes the 0 indexed element => it always returned the first element. Can you back up your possibility with an example? – CPHPython Jul 05 '18 at 11:00
  • 1
    @CPHPython A bit artificial example, but it demonstrates well my thoughts: http://sandbox.onlinephpfunctions.com/code/a30f92a932a31fbd7d3191435a481336f40ac4bc 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. – dmikam Jul 10 '18 at 10:19
10

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

if (!function_exists('array_key_last')) {
    function array_key_last($arr) {
        return array_key_first(array_reverse($arr, true));
    }
}
?>
AndreyP
  • 2,510
  • 1
  • 29
  • 17
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
  • 30,738
  • 21
  • 105
  • 131
Jacob Topping
  • 126
  • 1
  • 8
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

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • `because the each() function does not copy the entire array.` +1 –  Aug 04 '13 at 00: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. – Carlos Goce Jul 22 '14 at 15:59
  • But each() receives an array by reference and the requirement of the initial questions is not to do so – dmikam Apr 24 '15 at 15:17
7

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
  • 30,738
  • 21
  • 105
  • 131
William Macdonald
  • 2,139
  • 2
  • 21
  • 27
  • 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. – random_user_name Mar 21 '13 at 15:23
  • 1
    If you are doing this, you might as well use `reset()` as the array pointer is reset before `foreach`is called anyway. – Tyzoid Oct 21 '14 at 16:34
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

tfont
  • 10,891
  • 7
  • 56
  • 52
  • 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. – Tyzoid Oct 21 '14 at 16:35
  • @Tyzoid he actually wrote [another answer here with your suggestion](https://stackoverflow.com/a/48410351/6225838), but he omitted your explanation... Thank you. – CPHPython Jul 04 '18 at 11:38
  • @Tyzoid: I made an additional answer/update awhile go: https://stackoverflow.com/a/48410351/1804013 – tfont Sep 14 '18 at 08:22
5

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
  • 30,738
  • 21
  • 105
  • 131
Bazi
  • 311
  • 1
  • 4
  • 10
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!

Chris Kempen
  • 9,491
  • 5
  • 40
  • 52
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'.

jmking
  • 259
  • 1
  • 6
4
<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo array_values($arr)[0]; // Outputs: Apple
?>

Other Example:

<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo current($arr); // Outputs: Apple
    echo reset($arr); // Outputs: Apple
    echo next($arr); // Outputs: Ball
    echo current($arr); // Outputs: Ball
    echo reset($arr); // Outputs: Apple
?>
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
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
  • 30,738
  • 21
  • 105
  • 131
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
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
  • 30,738
  • 21
  • 105
  • 131
dmikam
  • 992
  • 1
  • 18
  • 27
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.

pgee70
  • 3,707
  • 4
  • 35
  • 41
  • 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` – Zack Morris May 22 '21 at 21:51
1

This is not so simple response in the real world. Suppose that we have these examples of possible responses that you can find in some libraries.

$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;

var_dump('reset1', reset($array1));
var_dump('reset2', reset($array2));
var_dump('reset3', reset($array3));
var_dump('reset4', reset($array4)); // Warning

var_dump('array_shift1', array_shift($array1));
var_dump('array_shift2', array_shift($array2));
var_dump('array_shift3', array_shift($array3));
var_dump('array_shift4', array_shift($array4)); // Warning

var_dump('each1', each($array1));
var_dump('each2', each($array2));
var_dump('each3', each($array3));
var_dump('each4', each($array4)); // Warning

var_dump('array_values1', array_values($array1)[0]); // Notice
var_dump('array_values2', array_values($array2)[0]);
var_dump('array_values3', array_values($array3)[0]);
var_dump('array_values4', array_values($array4)[0]); // Warning

var_dump('array_slice1', array_slice($array1, 0, 1));
var_dump('array_slice2', array_slice($array2, 0, 1));
var_dump('array_slice3', array_slice($array3, 0, 1));
var_dump('array_slice4', array_slice($array4, 0, 1)); // Warning

list($elm) = $array1; // Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);

Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.

In my opinion, you have should that handler only with arrays.

Now talking about performance, assuming that we have always array, like this:

$elm = empty($array) ? null : ...($array);

...you would use without errors:
$array[count($array)-1];
array_shift
reset
array_values
array_slice

array_shift is faster than reset, that is more fast than [count()-1], and these three are faster than array_values and array_slice.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steven Koch
  • 629
  • 7
  • 9
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.

Ataboy Josef
  • 2,087
  • 3
  • 22
  • 27
1

I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys() or array_values(), so I usually define this:

function array_first(array $f) {
    foreach ($f as $v) {
        return $v;
    }
    throw new Exception('array was empty');
}
Jesse
  • 6,725
  • 5
  • 40
  • 45
1

You can get the first element by using this coding:

$array_key_set = array_keys($array);
$first_element = $array[$array_key_set[0]];

Or use:

$i=0;
foreach($array as $arr)
{
  if($i==0)
  {
    $first_element=$arr;
    break;
  }
 $i++;
}
echo $first_element;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Karthikeyan Ganesan
  • 1,901
  • 20
  • 23
  • 2
    Why not just break out of the loop? `foreach ($array as $arr) { $first_element = $arr; break; }` – Blue Sep 13 '18 at 17:48
  • 1
    The `$i` if statements are completely irrelevant, and you can simply exclude them all together. `$i` will ALWAYS be 0 on the first loop, it will ALWAYS break out before ever reaching `$i++;` – Blue Sep 17 '18 at 14:42
  • Completely equivalent to return $array[0]; – Joe Love Jan 15 '20 at 21:41
1

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.

Progrock
  • 7,373
  • 1
  • 19
  • 25
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())));
Warbo
  • 2,611
  • 1
  • 29
  • 23
0

Also worth bearing in mind is the context in which you're doing this, as an exhaustive check can be expensive and not always necessary.

For example, this solution works fine for the situation in which I'm using it (but obviously it can't be relied on in all cases...)

 /**
 * A quick and dirty way to determine whether the passed in array is associative or not, assuming that either:<br/>
 * <br/>
 * 1) All the keys are strings - i.e. associative<br/>
 * or<br/>
 * 2) All the keys are numeric - i.e. not associative<br/>
 *
 * @param array $objects
 * @return boolean
 */
private function isAssociativeArray(array $objects)
{
    // This isn't true in the general case, but it's a close enough (and quick) approximation for the context in
    // which we're using it.

    reset($objects);
    return count($objects) > 0 && is_string(key($objects));
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dan King
  • 3,412
  • 5
  • 24
  • 23
  • What about `array(13, 'foo' => 'bar')` ? – hsz Dec 09 '13 at 13:08
  • Like I said, it doesn't work in all cases, but it's much cheaper than most of the other solutions and works fine in many (perhaps even most?) of the situations in which you're likely to need it. Please see the assumptions in the method comment. – Dan King Dec 11 '13 at 15:48
0

Nice one with a combination of array_slice and implode:

$arr = array(1, 2, 3);
echo implode(array_slice($arr, 0, 1));
// Outputs 1

/*---------------------------------*/

$arr = array(
    'key_1' => 'One',
    'key_2' => 'Two',
    'key_3' => 'Three',
);
echo implode(array_slice($arr, 0, 1));
// Outputs One
Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58
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
  • 30,738
  • 21
  • 105
  • 131
-3

There are too many answers here, and the selected answer will work for most of the cases.

In my case, I had a 2D array, and array_values for some odd reason was removing the keys on the inner arrays. So I end up with this:

$keys = array_keys($myArray); // Fetches all the keys
$firstElement = $myArray[$keys[0]]; // Get the first element using first key
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Usman Shaukat
  • 1,315
  • 16
  • 22
-7

If you are using Laravel you can do:

$array = ['a', 'b', 'c'];
$first = collect($array)->first();
pableiros
  • 14,932
  • 12
  • 99
  • 105
-10

Finding the first and last items in an array:

// Get the first item in the array
print $array[0]; // Prints 1

// Get the last item in the array
print end($array);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun Kushwaha
  • 1,136
  • 1
  • 8
  • 8
  • 8
    This will only work if you have an array that has consecutively numbered keys, beginning with 0 and ending with count()-1. It won't work in the case of the OP's array. – some-non-descript-user Jul 15 '15 at 12:42
  • Also even when using numeric keys it isn't said that zero is the first key. The order of adding is important. ```php $x = [1 => 'one', 0 => 'zero']; var_dump(reset($x)); string(3) "one" ``` – Danny Van Der Sluijs Dec 23 '21 at 08:23