PHP - Get key name of array value

前端 未结 9 1434
暗喜
暗喜 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:40

    you can use key function of php to get the key name:

    <?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);
         }
    ?>
    

    like here : PHP:key - Manual

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

    Yes you can infact php is one of the few languages who provide such support..

    foreach($arr as $key=>$value)
    {
    
    }
    
    0 讨论(0)
  • 2020-11-29 17:46

    Here is another option

    $array = [1=>'one', 2=>'two', 3=>'there'];
    $array = array_flip($array);
    echo $array['one']; 
    
    0 讨论(0)
提交回复
热议问题