php array get first element

get first and last element in array

hey there i have this array:

how to get the first and the last element out from this array, so i will have:

anybody knows how to get those elements from the array?

i already tried this:

6 Answers 6

reset() and end() does exactly this.

reset() : Returns the value of the first array element, or FALSE if the array is empty.

end() : Returns the value of the last element or FALSE for empty array.

NOTE: This will reset your array pointer meaning if you use current() to get the current element or you’ve seeked into the middle of the array, reset() and end() will reset the array pointer (to the beginning and to the end):

As of PHP 7.3, array_key_first and array_key_last is available

You can use reset() to get the first:

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

And end() to get the last:

end() advances array’s internal pointer to the last element, and returns its value.

php array get first element. Смотреть фото php array get first element. Смотреть картинку php array get first element. Картинка про php array get first element. Фото php array get first element

For first element: current($arrayname);

For last element: end($arrayname);

current(): The current() function returns the value of the current element in an array. Every array has an internal pointer to its «current» element, which is initialized to the first element inserted into the array.

Источник

array_shift

(PHP 4, PHP 5, PHP 7, PHP 8)

array_shift — Извлекает первый элемент массива

Описание

array_shift() извлекает первое значение массива array и возвращает его, сокращая размер array на один элемент. Все числовые ключи будут изменены таким образом, что нумерация массива начнётся с нуля, в то время как строковые ключи останутся прежними.

Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.

Список параметров

Возвращаемые значения

Примеры

Пример #1 Пример использования array_shift()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 30 notes

Using array_shift over larger array was fairly slow. It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn’t need to reindex the array and will preserve keys if you want it to (didn’t matter in my case).

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop. It also requires sequential numeric keys.

Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me 😉

Here is a little function if you would like to get the top element and rotate the array afterwards.

As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn’t return the first element by reference. This may seem like very unexpected behaviour. If you’re working with a collection of references (in my case XML Nodes) this should do the trick.

class ArrayShiftReferenceTest extends UnitTestCase
<

For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

This function will save the key values of an array, and it will work in lower versions of PHP:

To remove an element from the MIDDLE of an array (similar to array_shift, only instead of removing the first element, we want to remove an element in the middle, and shift all keys that follow down one position)

Note that this only works on enumerated arrays.

//———————————————————-
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//———————————————————-

If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.

?>

its like foreach but each time the value is removed from the array so it eventually ends up empty

3 Airport in the array

LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead

0 Airport left in the array

Here’s a utility function to parse command line arguments.

/**
* CommandLine class
*
* @package Framework
*/
/**
* Command Line Interface (CLI) utility class.
*
* @author Patrick Fisher

* @since August 21, 2009
* @package Framework
* @subpackage Env
*/
class CommandLine <

/**
* PARSE ARGUMENTS
*
* [pfisher

Источник

How to Get the First Element of an Array in PHP?

Analysis and round-up of various techniques to get the first element of a PHP array

Get First Element of an Array With Sequential Numeric Indexes

It’s fairly easy and straightforward to get the first element of a sequential array in PHP. Consider for example the following array:

Accessing the First Element of Array Directly:

Using list() :

Get First Element of an Out-Of-Order or Non-Sequential Array

In PHP, there are a number of ways you could access the value of the first element of an out-of-order (or non-sequential) array. Please note that we’ll be using the following array for all the examples that follow:

Using reset() :

The PHP reset() function not only resets the internal pointer of the array to the start of the array, but also returns the first array element, or false if the array is empty. This method has a simple syntax and support for older PHP versions:

Be careful when resetting the array pointer as each array only has one internal pointer and you may not always want to reset it to point to the start of the array.

Without Resetting the Original Array:

If you do not wish to reset the internal pointer of the array, you can work around it by creating a copy of the array simply by assigning it to a new variable before the reset() function is called, like so:

As you can see from the results, we’ve obtained the first element of the array without affecting the original.

Using array_slice() :

The advantage to using this approach is that it doesn’t modify the original array. However, on the flip side there could potentially be an array offset problem when the input array is empty. To resolve that, since our array only has one element, we could use the following methods to return the first (also the only) element:

Using array_values() :

This method may only be useful if the array is known to not be empty.

Using array_reverse() :

Using foreach Loop:

We can simply make use of the foreach loop to go one round and immediately break (or return ) after we get the first value of the array. Consider the code below:

Although it takes up a few lines of code, this would be the fastest way as it’s using the language construct foreach rather than a function call (which is more expensive).

This could be written as a reusable function as well:

Hope you found this post useful. It was published 28 Jul, 2016 (and was last revised 31 May, 2020 ). Please show your love and support by sharing this post.

Источник

Get first key in a (possibly) associative array?

What’s the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:

23 Answers 23

2019 Update

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info.

It’s essentially the same as your initial code, but with a little less overhead, and it’s more obvious what is happening.

If you wanted the key to get the first value, reset actually returns it:

There is one special case to watch out for though (so check the length of the array first):

php array get first element. Смотреть фото php array get first element. Смотреть картинку php array get first element. Картинка про php array get first element. Фото php array get first element

Interestingly enough, the foreach loop is actually the most efficient way of doing this.

Since the OP specifically asked about efficiency, it should be pointed out that all the current answers are in fact much less efficient than a foreach.

I did a benchmark on this with php 5.4, and the reset/key pointer method (accepted answer) seems to be about 7 times slower than a foreach. Other approaches manipulating the entire array (array_keys, array_flip) are obviously even slower than that and become much worse when working with a large array.

Foreach is not inefficient at all, feel free to use it!

Edit 2015-03-03:

Benchmark scripts have been requested, I don’t have the original ones but made some new tests instead. This time I found the foreach only about twice as fast as reset/key. I used a 100-key array and ran each method a million times to get some noticeable difference, here’s code of the simple benchmark:

Источник

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

If I had an array like:

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?

16 Answers 16

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

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

php array get first element. Смотреть фото php array get first element. Смотреть картинку php array get first element. Картинка про php array get first element. Фото php array get first element

php array get first element. Смотреть фото php array get first element. Смотреть картинку php array get first element. Картинка про php array get first element. Фото php array get first element

PHP 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:

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

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

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

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:

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+

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

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *