This might sounds like a silly question. How do I get the 1st value of an array without knowing in advance if the array is associative or not?
In order to get the 1st element of an array I thought to do this:
function Get1stArrayValue($arr) { return current($arr); }
is it ok? Could it create issues if array internal pointer was moved before function call? Is there a better/smarter/fatser way to do it?
Thanks!
-
1I wonder how you define a "first" element in an associative array ;)phunehehe– phunehehe02/09/2010 15:36:32Commented Feb 9, 2010 at 15:36
3 Answers 3
A better idea may be to use reset which "rewinds array's internal pointer to the first element and returns the value of the first array element"
Example:
function Get1stArrayValue($arr) { return reset($arr); }
As @therefromhere pointed out in the comment below, this solution is not ideal as it changes the state of the internal pointer. However, I don't think it is much of an issue as other functions such as array_pop also reset it.
The main concern that it couldn't be used when iterating over an array isn't an problem as foreach
operates on a copy of the array. The PHP manual states:
Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.
This can be shown using some simple test code:
$arr = array("a", "b", "c", "d");
foreach ( $arr as $val ){
echo reset($arr) . " - " . $val . "\n";
}
Result:
a - a
a - b
a - c
a - d
-
5Worth noting that since it rewinds the internal pointer then you shouldn't do this if you're in the middle of iterating this array.John Carter– John Carter02/09/2010 15:32:15Commented Feb 9, 2010 at 15:32
-
Great Yacoby, therefor internal pointer is not affected by foreach loops.Marco Demaio– Marco Demaio02/09/2010 15:42:20Commented Feb 9, 2010 at 15:42
To get the first element for any array, you need to reset the pointer first. https://www.php.net/reset
function Get1stArrayValue($arr) {
return reset($arr);
}
If you don't mind losing the first element from the array, you can also use
array_shift()
- shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.
Or you could wrap the array into an ArrayIterator and use seek
:
$array = array("foo" => "apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(0);
echo $iterator->current(); // apple
If this is not an option either, use one of the other suggestions.