PHP - Get key name of array value

前端 未结 9 1433
暗喜
暗喜 2020-11-29 16:53

I have an array as the following:

function example() {
    /* some stuff here that pushes items with
        dynamically created key strings into an array */         


        
相关标签:
9条回答
  • 2020-11-29 17:23
    key($arr);
    

    will return the key value for the current array element

    http://uk.php.net/manual/en/function.key.php

    0 讨论(0)
  • 2020-11-29 17:27

    If the name's dynamic, then you must have something like

    $arr[$key]
    

    which'd mean that $key contains the value of the key.

    You can use array_keys() to get ALL the keys of an array, e.g.

    $arr = array('a' => 'b', 'c' => 'd')
    $x = array_keys($arr);
    

    would give you

    $x = array(0 => 'a', 1 => 'c');
    
    0 讨论(0)
  • 2020-11-29 17:29

    if you need to return an array elements with same value, use array_keys() function

    $array = array('red' => 1, 'blue' => 1, 'green' => 2);
    print_r(array_keys($array, 1));
    
    0 讨论(0)
  • 2020-11-29 17:36

    If you have a value and want to find the key, use array_search() like this:

    $arr = array ('first' => 'a', 'second' => 'b', );
    $key = array_search ('a', $arr);
    

    $key will now contain the key for value 'a' (that is, 'first').

    0 讨论(0)
  • 2020-11-29 17:37

    If i understand correctly, can't you simply use:

    foreach($arr as $key=>$value)
    {
      echo $key;
    }
    

    See PHP manual

    0 讨论(0)
  • 2020-11-29 17:37

    use array_keys() to get an array of all the unique keys.

    Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].

    http://php.net/manual/en/function.array-keys.php

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