Php gets 1st array value (associative or not)

This may seem like a silly question. How to get the first value of an array without knowing in advance if the array is associative or not?

To get the 1st element of the array, I decided to do this:

function Get1stArrayValue($arr) { return current($arr); }

this is normal? Can it cause problems if the internal array pointer was moved before the function call? Is there a better / smarter / fatser way to do this?

Thank!

+5
source share
3 answers

A better idea would be to use reset , which "rewinds the internal pointer of the array to the first element and returns the value of the first element of the array"

Example:

function Get1stArrayValue($arr) { return reset($arr); }

@therefromhere, , , . , , , , array_pop reset it.
, , , foreach . PHP :

, foreach , .

:

$arr = array("a", "b", "c", "d");
foreach ( $arr as $val ){
    echo reset($arr) . " - " . $val . "\n";
}

:

a - a
a - b
a - c
a - d
+9

, reset . http://ca3.php.net/reset

function Get1stArrayValue($arr) { 
  return reset($arr); 
}
+1

,

array_shift()- shifts the first value of the array and returns it, reducing the array by one element and moving everything down. All the numeric keys of the array will be changed to start counting from scratch until the literal keys are affected.

Or you can wrap the array in 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 also not an option, use one of the other suggestions.

0
source

All Articles