How to find first/second element of associative array when keys are unknown?
use these functions to set the internal array pointer:
http://ch.php.net/manual/en/function.reset.php
http://ch.php.net/manual/en/function.end.php
And this one to get the actual element: http://ch.php.net/manual/en/function.current.php
reset($groups);
echo current($groups); //the first one
end($groups);
echo current($groups); //the last one
If you wanna have the last/first key then just do something like $tmp = array_keys($groups);
.
$array = array('Alpha' => 1.1,'Bravo' => 2.2,'Charlie' => 3.3,'Delta' => 4.4,'Echo' =>5.5, 'Golf' => 6.6);
$pos = 3;
function getAtPos($tmpArray,$pos) {
return array_splice($tmpArray,$pos-1,1);
}
$return = getAtPos($array,$pos);
var_dump($return);
OR
$array = array('Alpha' => 1.1,'Bravo' => 2.2,'Charlie' => 3.3,'Delta' => 4.4,'Echo' =>5.5, 'Golf' => 6.6);
$pos = 3;
function getAtPos($tmpArray,$pos) {
$keys = array_keys($tmpArray);
return array($keys[$pos-1] => $tmpArray[$keys[$pos-1]]);
}
$return = getAtPos($array,$pos);
var_dump($return);
EDIT
Assumes $pos = 1 for the first element, but easy to change for $pos = 0 by changing the $pos-1 references in the functions to $pos