[php] php: how to get associative array key from numeric index?

If I have:

$array = array( 'one' =>'value', 'two' => 'value2' );

how do I get the string one back from $array[1] ?

This question is related to php key associative-array

The answer is


Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

$array = array( 'one' =>'value', 'two' => 'value2' );

$allKeys = array_keys($array);
echo $allKeys[0];

Which will output:

one

You might do it this way:

function asoccArrayValueWithNumKey(&$arr, $key) {
   if (!(count($arr) > $key)) return false;
   reset($array);
   $aux   = -1;
   $found = false;
   while (($auxKey = key($array)) && !$found) {
      $aux++;
      $found = ($aux == $key);
   }
   if ($found) return $array[$auxKey];
   else return false;
}

$val = asoccArrayValueWithNumKey($array, 0);
$val = asoccArrayValueWithNumKey($array, 1);
etc...

Haven't tryed the code, but i'm pretty sure it will work.

Good luck!


If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:

echo array_keys($array)[$i];

If it is the first element, i.e. $array[0], you can try:

echo key($array);

If it is the second element, i.e. $array[1], you can try:

next($array);
echo key($array);

I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.


The key function helped me and is very simple:

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

Example:

<?php
    $array = array(
        'fruit1' => 'apple',
        'fruit2' => 'orange',
        'fruit3' => 'grape',
        'fruit4' => 'apple',
        'fruit5' => 'apple');

    // this cycle echoes all associative array
    // key where value equals "apple"
    while ($fruit_name = current($array)) {
        if ($fruit_name == 'apple') {
            echo key($array).'<br />';
        }
        next($array);
    }
?>

The above example will output:

fruit1<br />
fruit4<br />
fruit5<br />

$array = array( 'one' =>'value', 'two' => 'value2' );
$keys  = array_keys($array);
echo $keys[0]; // one
echo $keys[1]; // two

Or if you need it in a loop

foreach ($array as $key => $value)
{
    echo $key . ':' . $value . "\n";
}
//Result: 
//one:value
//two:value2

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?

Examples related to associative-array

How to insert a new key value pair in array in php? Rename a dictionary key How to update specific key's value in an associative array in PHP? Is there a way to create key-value pairs in Bash script? PHP combine two associative arrays into one array Are there dictionaries in php? Display array values in PHP Adding an item to an associative array Extract subset of key-value pairs from Python dictionary object? Java associative-array