There is a variety of ways to get the first element or value of an Array with PHP. Functions such as array_shift()
will aid in grabbing the first value, but it completely depends on the bigger picture. If you want to get the first element and discard of the array, maybe this function will be perfect.
My personal recommendation to grab the first value would be to use the numerical index of the array. It’s the simplest and you don’t have to worry about virtual pointers.
In this tutorial based article, we will explore the various ways to get the first element of an array. First of all, we must define an array with some dummy data.
The Array
The following array has been defined with some completely useless data to provide examples of consuming the very first value. In the following examples, the value we want to retrieve is “myFirstValue”.
$myArray = ["myFirstValue", "mySecondValue", "myThirdValue"];
Using the index of the array
This is my personal recommended method
All non-associative arrays have numeric exclusive indexing and therefore can be accessed with a number. The array defined earlier is a numerically indexed array and so each of the values has an associated number, starting from 0. The first value, of course, is index position zero, so we can use the following example to get the first element.
Example
// Index Pos 0 Index Pos 1 Index Pos 2
$myArray = ["myFirstValue", "mySecondValue", "myThirdValue"];
echo $myArray[0];
Output
myFirstValue
Using the current() function
The current() function can be used with caution due to its characteristics of grabbing the array value of which the virtual pointer is located. This virtual pointer is changed with other functions such as next()
and end()
.
Example 1
The first example assumes the array is untouched.
$myArray = ["myFirstValue", "mySecondValue", "myThirdValue"];
echo current($myArray);
Output
myFirstValue
Example 2
The second example assumes the array has had functions executed on it such as next()
and end()
(So the pointer isn’t at the start of the array)
$myArray = ["myFirstValue", "mySecondValue", "myThirdValue"];
reset($myArray); // Reset the pointer
echo current($myArray);
Output
myFirstValue
Further reading on the current()
function and the virtual pointer can be viewed on the PHP documentation.
The post Get The First Element Of An Array In PHP appeared first on Code Wall.
This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here