The other day I was programming in PHP and needed to get the first index in an associative array. There doesn’t appear to be a built in function to deal with this so I wrote my own.
PHP:
-
function getArrayFirstIndex($arr)
-
{
-
foreach ($arr as $key => $value)
-
return $key;
-
}
Here's a bit of code you can test it on:
PHP:
-
$arr['banana'] = "yellow";
-
$arr['apple'] = "apple";
-
$arr['orange'] = "orange";
-
-
$first_index = getArrayFirstIndex($arr);
-
The above code will output 'first index = banana'.
/* Pete Graham */
Comments 6
just use key() before you start traversing the array. Am I missing something about the problem?
Posted 12 Jun 2007 at 6:19 pm ¶Yes i think just using array_keys() to get all the indexes, which then means you have an array like [0] => array_key1, [1] => array_key2 etc. You can then use the index to get the key you are interested in.
Posted 17 Dec 2007 at 10:10 am ¶Why not simply use current($array); ?
Posted 23 Apr 2008 at 11:14 pm ¶You can use the key() function for an associative array.
This will return the first key name, eg $keyname = key($array);
You can then use next() and prev() to get keys that follow.
So if i quickly wanted the 3rd key id do this:
next($array);
next($array);
next($array);
$keyname = key($array);
The current() function is best used on
Posted 26 Jan 2009 at 2:08 pm ¶reset() returns first value
reset() followed by each() or key() should give you the first key/value
drawback: internal pointer gets lost using reset()
Posted 05 Jun 2009 at 1:05 pm ¶reset is much better, please update your (dirty) post
But you could make a more usefull function:
public static function getItemAt($collection,$index)
{
if ($index >= 0 && $index < count($collection))
{
$i = 0;
foreach ($collection AS $item)
{
if ($i++ == $index)
{
return $item;
}
}
}
return null;
Posted 03 Dec 2009 at 7:38 pm ¶}
Trackbacks & Pingbacks 1
[...] Despues de pasarme un rato googleando me topo de que php no trae una funcion para acceder al primer elemento de una matriz asociativa, Algo extrano de que php no tenga una funcion implicita para realizar esto, al final (como me lo imaginaba, pero no queria aceptar que no existira tal función )) recurri al amigo foreach como nos cuenta tech.petegraham.co.uk [...]
Post a Comment