tags:

views:

97

answers:

3

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!

+7  A: 

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
Yacoby
Worth noting that since it rewinds the internal pointer then you shouldn't do this if you're in the middle of iterating this array.
therefromhere
Great Yacoby, therefor internal pointer is not affected by foreach loops.
Marco Demajo
foreach works on a copy of the array
meouw
+1  A: 

To get the first element for any array, you need to reset the pointer first. http://ca3.php.net/reset

function Get1stArrayValue($arr) { 
  return reset($arr); 
}
Yada
A: 

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.

Gordon
I do mind losing the 1st element. Thanks anyway!
Marco Demajo