Php массив первое значение

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

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.

To note: $arr = array(/* stuff */); $val = $arr? reset($arr): /* value to indicate array is empty */;

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

Источник

Получить первое значение массива (PHP)

В каждом массиве PHP есть внутренний указатель на «текущий» элемент. И если не использовалась функция next() , то ее вызов вернет текущее значение массива, в данном случае первое. Если вызов функции next() , был осуществлен, то сперва нужно воспользоваться функцией reset() .

Функция array_shift()

Функция array_shift() извлекает первое значение массива и возвращает его.

Третий способ

Третий способ не самый лучший, но, если вы уверены что все ключи массива цифровые или вам неважны ключи, то способ тоже подойдет.

Категории

Читайте также

  • Получить последнее значение массива (PHP)
  • Получить первый элемент массива (JavaScript)
  • Случайный элемент массива (JavaScript)
  • Получить массив ключей (PHP)
  • Найти и удалить элемент массива (PHP)
  • Получить последовательность элементов массива (PHP)
  • Массив уникальных значений (JavaScript)
  • Умножить массив на число (PHP)
  • Как удалить элемент ассоциативного массива (JavaScript)
  • Ассоциативный массив в JavaScript
  • Преобразовать массив в объект (PHP)
  • Элементы массива в случайном порядке (PHP)

Комментарии

«Функция array_shift() извлекает последнее значение массива и возвращает его.»
array_shift() извлекает первое значение

Вход на сайт

Введите данные указанные при регистрации:

Социальные сети

Вы можете быстро войти через социальные сети:

Источник

Как получить первый элемент массива в php

Итак, у нас есть массив $arr и нужно получить первый элемент этого массива.

Нельзя просто сделать так:

Элемент с индексом 0 может быть просто не определен. Например в случае если массив ассоциативный, либо мы сделали unset($arr[0]) .

Способ 1

Используя reset мы получаем первый элемент, однако есть один побочный эффект: указатель массива также сбрасывается на первый элемент. Хотя в принципе эта функция и предназначена для сброса указателя. Документация по функции reset().

Обратите внимание: если массив пустой reset() вернет false , и этот результат будет неотличим от случая, когда массив не пустой, но содержит false в качестве первого элемента.

$a = array(); $b = array(false, true, true); var_dump(reset($a) === reset($b)); //bool(true)

Способ 2

Можно воспользоваться функцией array_shift — она извлекает первый элемент и при этом удаляет его из переданного массива. Документация по array_shift().

Способ 3

Написать свою функцию для этих целей:

function array_first($array, $default = null) < foreach ($array as $item) < return $item; >return $default; >

Преимущество в том, что она не меняет исходный массив. Также вы можете передать параметр $default , который будет использоваться в качестве значения по умолчанию, если массив пустой.

Кстати во фреймворке Laravel эта функция уже определена и позволяет указать еще и callback, в который можно передать условие. Можно например взять первый элемент, который больше 10 или первый элемент, который не является числом.

Вот код более совершенной функции:

function array_first($array, callable $callback = null, $default = null) if (is_null($callback)) < if (empty($array)) < return $default instanceof Closure ? $default() : $default; >foreach ($array as $item) < return $item; >> foreach ($array as $key => $value) < if (call_user_func($callback, $value, $key)) < return $value; >> return $default instanceof Closure ? $default() : $default; >

Ее можно использовать например так:

$array = [100, 200, 300]; $first = array_first($array, function ($value, $key) < return $value >= 150; >); echo $first; // 200

Способ 4

Функция current() также пригодна для получения первого элемента массива.
Пример использования:

$transport = array('foot', 'bike', 'car', 'plane'); $mode = current($transport); // $mode = 'foot';

Точнее эта функция используется для возвращения элемента, на котором находится внутренний указатель массива. В большинстве случаев указатель на первом элементе, однако есть ситуации, когда может быть возвращен не первый элемент.

$transport = array('foot', 'bike', 'car', 'plane'); next($transport); // перемещаем указатель вперед (http://php.net/manual/ru/function.next.php) $mode = current($transport); // $mode = 'bike'; — т. е. вернулся уже второй элемент массива.

Спасибо комментатору Alexey Berlinskiy, за этот способ.

Если вы еще знаете способы получения первого элемента — пишите в комментариях.

Источник

get first and last element in array

Have a look at reset() and end() . P.S. 0 will always be the 1st element, and for the last you can do $arr[count($arr)-1] .

6 Answers 6

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

yeah but take a look at my array, when i use your code, i get: «Warning: reset() expects parameter 1 to be array, null given» and the same for end()

You can accessing array elements always with square bracket syntax. So to get the first use 0 , as arrays are zero-based indexed and count($arr) — 1 to get the last item.

$firstEle = $arr[0]; $lastEle = $arr[count($arr) - 1]; 

As of PHP 7.3, array_key_first and array_key_last is available

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

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.

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

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.

end(): The end() function moves the internal pointer to, and outputs, the last element in the array. Related methods: current() — returns the value of the current element in an array

$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6); $first = current($array); $last = end($array); echo 'First Element: '.$first.' :: Last Element:'.$last; 

Output result:

First Element: 24 :: Last Element:24.6 

Источник

Читайте также:  If isset server php auth user
Оцените статью