PHP: Get First Index in Associative Array

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:
  1. function getArrayFirstIndex($arr)
  2. {
  3. foreach ($arr as $key => $value)
  4. return $key;
  5. }

Here's a bit of code you can test it on:

PHP:
  1. $arr['banana'] = "yellow";
  2. $arr['apple'] = "apple";
  3. $arr['orange'] = "orange";
  4.  
  5. $first_index = getArrayFirstIndex($arr);
  6.  
  7. echo "first index =".$first_index;

The above code will output 'first index = banana'.

/* Pete Graham */

Comments 6

  1. Charles Rowe wrote:

    just use key() before you start traversing the array. Am I missing something about the problem?

    Posted 12 Jun 2007 at 6:19 pm
  2. ian wrote:

    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
  3. Peter Goodman wrote:

    Why not simply use current($array); ?

    Posted 23 Apr 2008 at 11:14 pm
  4. Adam wrote:

    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
  5. benjy77 wrote:

    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
  6. Tom wrote:

    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

  1. From » Obtener el primer valor de una matriz asociativa en PHP » Pensando! » Archivo del Blog on 09 Jun 2007 at 12:25 am

    [...] 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

Your email is never published nor shared. Required fields are marked *