If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
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?
If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
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?
You can try this.
To get first value of the array :-
To get the first key of the array
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use
array_key_first
. If you're sure that your array has values it in then you can just do:More likely, you'll want to handle the case where the array is empty:
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
Use reset() function to get the first item out of that array without knowing the key for it like this.
output // 400
We can do
$first = reset($array);
Instead of
As
reset()
returns the first element of the array after reset;
another easy and simple way to do it use array_values