- Get First Element of Array in php
- Getting the First Element of an Array in php with current()
- Getting the First Element of an Array in php with reset()
- Get the First Element of an Array in php with array_values()
- How to Get the First N Elements of a php Array
- Other Articles You’ll Also Like:
- About The Programming Expert
- Как получить первый элемент массива в php
- Способ 1
- Способ 2
- Способ 3
- Способ 4
- How to Get the First Element of an Array in PHP
- Using array_values()
- Using reset()
- Using array_shift
- Using array_pop
- How to find the first key
- How to Get the First Element of an Array in PHP
- Example
- Example
- Example
- Related FAQ
Get First Element of Array in php
To get the first element of an array in php, the easiest way is by accessing the first element directly.
$array = array(1, 2, 3, 4, 5); echo $array[0]; // Output: 1
Another way to get the first element of an array is with the current() function.
$array = array(1, 2, 3, 4, 5); echo current($array); // Output: 1
A third way to get the first element of an array is with the reset() function.
$array = array(1, 2, 3, 4, 5); echo reset($array); // Output: 1
One final way to get the first element of an array is with the php array_values() function.
$array = array(1, 2, 3, 4, 5); echo array_values($array)[0]; // Output: 1
When working with arrays in php, it can be valuable to be able to easily filter and get only specific values from your array.
One such situation is when you want to get the first element from a php array.
There are a number of ways to get the first element from a php array, and the easiest way is to access the first element directly by accessing the ‘0’ position.
Below is an example of how to print the first element of a php array.
$array = array(1, 2, 3, 4, 5); echo $array[0]; // Output: 1
If you are looking to get the last element of a php array, the easiest way is with the end() function.
$array = array(1, 2, 3, 4, 5); echo end($array); // Output: 5
Getting the First Element of an Array in php with current()
Another way that you can get the first element of an array in php is with the current() function.
current() returns the value of the element in an array which the internal pointer is currently pointing to. Usually, the current elemnt is the first inserted item into the array.
If we use the current() function on an array, we get the first element of the array.
Below is how to use current() to get the first element of the array.
$array = array(1, 2, 3, 4, 5); echo current($array); // Output: 1
Getting the First Element of an Array in php with reset()
Another way that you can get the first element of an array in php is with the reset() function.
reset() is used to move any array’s internal pointer to the first element of that array. The reset() function resets the internal pointer to point to the first element of the array.
If we use the reset() function on an array, we get the first element of the array.
Below is how to use reset() to get the first element of the array.
$array = array(1, 2, 3, 4, 5); echo reset($array); // Output: 1
Get the First Element of an Array in php with array_values()
One final way that you can get the first element of an array in php is with the array_values() function.
array_values() creates a new array with just the values of the passed array. Then, after getting just the array values, we can access the first element.
Below is how to use array_values() to get the first element of the array.
$array = array(1, 2, 3, 4, 5); echo array_values($array)[0]; // Output: 1
How to Get the First N Elements of a php Array
If you are looking to get more than just the first element, we can get the first n elements of a php array with the array_slice() function.
You can pass php array_slice() function a starting position and ending position, and get the elements in the array between those two positions.
To get the first n elements of an array in php, pass ‘0’ and ‘n’ to array_slice().
Below is a simple example of how to get the first three elements of an array using php.
$array = array(1, 2, 3, 4, 5); echo var_dump(array_slice($array, 0, 3)); // Output: array(3) < [0]=>int(1) [1]=> int(2) [2]=> int(3) >
Hopefully this article has been useful for you to learn how to get the first element of an array when using php.
Other Articles You’ll Also Like:
- 1. php print_r() Function- Get Information about Variables in php
- 2. Get Current Month of Date in php
- 3. Remove Duplicates from Array in php with array_unique()
- 4. php sinh – Find Hyperbolic Sine of Number Using php sinh() Function
- 5. php array_fill() – Create Array of Length N with Same Value
- 6. php array_intersect() – Find Intersection of Two or More Arrays in php
- 7. Reversing an Array in php with array_reverse() Function
- 8. php property_exists() – Check if Property Exists in Class or Object
- 9. Delete Cookie Using php
- 10. php is_float() Function – Check if Variable is Float in php
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
Как получить первый элемент массива в 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
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.
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 ?>
Related FAQ
Here are some more FAQ related to this topic: