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

后端 未结 9 2134
臣服心动
臣服心动 2020-12-02 15:21

If I have:

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

how do I get the string one back from $ar

相关标签:
9条回答
  • 2020-12-02 15:49

    Or if you need it in a loop

    foreach ($array as $key => $value)
    {
        echo $key . ':' . $value . "\n";
    }
    //Result: 
    //one:value
    //two:value2
    
    0 讨论(0)
  • 2020-12-02 15:53

    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.

    0 讨论(0)
  • You don't. Your array doesn't have a key [1]. You could:

    • Make a new array, which contains the keys:

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

      But the value "one" is at $newArray[0], not [1].
      A shortcut would be:

      echo current(array_keys($array));
      
    • Get the first key of the array:

       reset($array);
       echo key($array);
      
    • Get the key corresponding to the value "value":

      echo array_search('value', $array);
      

    This all depends on what it is exactly you want to do. The fact is, [1] doesn't correspond to "one" any which way you turn it.

    0 讨论(0)
提交回复
热议问题