Getting the key of the only element in a PHP array

前端 未结 6 826
暖寄归人
暖寄归人 2021-01-17 12:17

The key of the associative array is dynamically generated. How do I get the \"Key\" of such an array?

$arr = array (\'dynamic_key\' => \'Value\');
         


        
相关标签:
6条回答
  • 2021-01-17 12:55

    You can use array_shift(array_keys($arr)) (with array_values for getting the value), but it still does a loop internally.

    0 讨论(0)
  • 2021-01-17 13:02
    $keys = array_keys($arr);
    echo $keys[0];
    

    Or use array_values() for the value.

    0 讨论(0)
  • 2021-01-17 13:03

    do you mean that you have the value of entry and want to get the key ?

    array_search ($value, $array) 
    

    Returns the key for needle if it is found in the array, FALSE otherwise.

    If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

    more details : http://php.net/manual/en/function.array-search.php

    0 讨论(0)
  • 2021-01-17 13:10

    edit: http://php.net/each says:

    each

    Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.


    Using key() is fine.
    If you're going to fetch the value anyway you can also use each() and list().

    $arr = array ('dynamic_key' => 'Value');
    list($key, $value) = each($arr);
    echo $key, ' -> ', $value, "\n";
    

    prints dynamic_key -> Value

    0 讨论(0)
  • 2021-01-17 13:16

    What about array_keys()?

    It does return an array though...

    0 讨论(0)
  • 2021-01-17 13:20

    Shortest, easiest and most independent solution is:

    $key   = key($arr);
    $value = reset($arr);
    
    0 讨论(0)
提交回复
热议问题