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

后端 未结 9 2190
臣服心动
臣服心动 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:43

    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:

     '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).'
    '; } next($array); } ?>

    The above example will output:

    fruit1
    fruit4
    fruit5

提交回复
热议问题