First array item php

How to Get the First Element of an Array in PHP

If you know the exact index or key of an array you can easily get the first element, like this:

Example

 "Apple", "b" => "Ball", "c" => "Cat"); echo $fruits["a"]; // Outputs: Apple ?>

However, there are certain situations where you don’t know the exact index or key of the first element. In that case you can use the array_values() function which returns all the values from the array and indexes the array numerically, as shown in the following example:

Example

 "Apple", 5 => "Ball", 11 => "Cat"); echo array_values($arr)[0]; // Outputs: Apple ?>

Alternativly, you can also use the reset() function to get the first element.

The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

Читайте также:  Проверка всей mysql php

You can also use the current() function to get the first element of an array. This function returns the current element in an array, which is the first element by default unless you’ve re-positioned the array pointer, otherwise use the reset() function. Here’s an example:

Example

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

Here are some more FAQ related to this topic:

Источник

Как получить первый элемент массива в 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, за этот способ.

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

Источник

How to Get the First Element of an Array in PHP

Here, you have the opportunity of finding the most proper solutions on how to get the first element of an array in PHP. Let’s consider several options below.

Let’s see how to get the first element of an array when you know the particular index or the key of the array. In that case, you can retrieve the first element straightforwardly by running this code:

 // A sample indexed array $cities = ["Milan", "London", "Paris"]; echo $cities[0]; // Outputs: Milan // A sample associative array $fruits = ["a" => "Banana", "b" => "Ball", "c" => "Dog"]; echo $fruits["a"]; // Outputs: Banana ?>

In the circumstances when you don’t know the exact key or index of the array, you can use the functions that are demonstrated below.

Using array_values()

In the circumstances when you don’t know the exact key or index of the array, you can use the array_values() function. It is capable of returning all the values of the array and indexing the array numerically.

The example of using array_values() is demonstrated below:

 $array = [3 => "Apple", 5 => "Ball", 11 => "Cat"]; echo array_values($array)[0]; // Outputs: Apple ?>

Using reset()

Now, let’s consider an alternative method to get the first element of an array.

It is the PHP reset() function. It is used for setting the internal pointer of the array to its first element and returning the value of the first array element. In the case of a failure, it returns FALSE or an empty array.

 $arr = [4 => 'apple', 7 => 'banana', 13 => 'grapes']; echo reset($arr); // Echoes "apple" ?>

Using array_shift

Another helpful method of getting the first element of a PHP array is using array_shift .

The example of using the array_shift function will look as follows:

 $array = [4 => 'apple', 7 => 'banana', 13 => 'grapes']; $values = array_values($array); echo array_shift($values); ?>

Using array_pop

The example of using array_pop to get the first element of an array in PHP is shown below:

 $array = [4 => 'apple', 7 => 'banana', 13 => 'grapes']; $reversedArray = array_reverse($array); echo array_pop($reversedArray); ?>

After checking out all the methods and examples above, you can choose the one that suits your project more.

How to find the first key

If you want to find the first key of the array instead of the value you should use the array_keys function.

 $array = [4 => 'apple', 7 => 'banana', 13 => 'grapes']; $keys = array_keys($array); echo $keys[0]; ?>

Источник

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

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:

$sequentialArray = ['foo', 'bar', 'baz'];

Accessing the First Element of Array Directly:

echo $sequentialArray[0] ?? ''; // output: 'foo'

By using ?? (the null coalescing operator) you can return the first index if it’s set and not null, or return an empty string otherwise.

Using list() :

// PHP 4+ list($first) = $sequentialArray; // or, alternatively in PHP 7.1+ [$first] = $sequentialArray; echo $first; // output: 'foo'

For a non-sequential array this would throw an error because list() tries to unpack array values sequentially (starting from the first index — i.e. 0 ). However, starting from PHP 7.1, you can specify the specific key you’re looking to unpack but we’re not covering that since it’s not within the scope of this article.

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:

$names = [9 => 'john', 15 => 'jane', 22 => 'wayne'];

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:

// PHP 4+ echo reset($names); // output: "john"

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:

$namesCopy = $names; next($names); // move array pointer to 2nd element echo reset($namesCopy); // output: "john" echo current($names); // output: "jane"

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

Using array_slice() :

// PHP 5.4+ echo array_slice($names, 0, 1)[0]; // output: "john"

Please note that by default array_slice() reorders and resets the numeric array indices. This can be changed however, by specifying the fourth parameter preserve_keys as true .

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:

// PHP 4+ $namesCopy = array_slice($names, 0, 1); echo array_shift($namesCopy); // output: null if array is empty echo array_pop($namesCopy); // output: null if array is empty echo implode($namesCopy); // output: '' if array is empty // PHP 7+ echo $names_copy[0] ?? ''; // output: '' if array index is not set or its value is null
  • You must note though that using array_shift() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged.
  • Using both array_shift() and array_pop() resets the array pointer of the input array after use, but in our case that doesn’t matter since we’re using a copy of the original array, that too with only a single element.

Using array_values() :

// PHP 5.4+ echo array_values($names)[0]; // output: "john"

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

In PHP 7+, we can use ?? (the null coalescing operator) to return the first index if it’s set and not null, or return an empty string otherwise. For example:

// PHP 7+ echo array_values($names)[0] ?? '';

Using array_reverse() :

// PHP 4+ array_pop(array_reverse($names)); // output: "john"
  • By default array_reverse() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged unless a second parameter preserve_keys is specified as true .
  • This method is not recommended as it may do unwanted longer processing on larger arrays to reverse them prior to getting the first value.

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:

// PHP 4+ foreach ($names as $name) < echo $name; break; // break loop after first iteration >// or the shorter form foreach ($names as $name) break; // break loop after first iteration echo $name; // output: 'john'

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:

function array_first_value(array $arr) < foreach ($arr as $fv) < return $fv; >return null; // return null if array is empty >

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.

Источник

Оцените статью