Search value in php array and get all keys

后端 未结 3 1834
眼角桃花
眼角桃花 2021-02-12 14:50

Is there any better (= quicker ) solution to get all keys of value in array than foreach loop with if?

$array = array(\'apple\', \'orange\', \'pear\', \'banana\'         


        
相关标签:
3条回答
  • 2021-02-12 15:08
    function array_search_values( $m_needle, $a_haystack, $b_strict = false){
        return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
    }
    
    $array = array('apple', 'orange', 'pear', 'banana', 'apple',
    'pear', 'kiwi', 'kiwi', 'kiwi');
    
    print_r( array_search_values( 'kiwi', $array,true));
    
    0 讨论(0)
  • 2021-02-12 15:11

    Alternatively, you could also use array_keys in this case, and providing the second parameter needle:

    $array = array('apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi');
    $searchObject = 'kiwi';
    $keys = array_keys($array, $searchObject);
    print_r($keys);
    

    Sample Output

    0 讨论(0)
  • 2021-02-12 15:26

    Try this :)

    <?php
        $array = array('apple', 'orange', 'pear', 'banana', 'apple','pear', 'kiwi', 'kiwi', 'kiwi');
        $count = count($array);
        $str_to_search = 'kiwi';
        for($i=0;$i<$count;$i++){
            if($array[$i] == $str_to_search){
                echo $i.",";
            }
        }
    ?>
    
    0 讨论(0)
提交回复
热议问题