23

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', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r($array); will give me:

Array ( [0] => apple [1] => orange [2] => pear [3] => banana [4] => apple [5] => pear [6] => kiwi [7] => kiwi [8] => kiwi )

array_search("kiwi", $array); will give me 6

But I want all keys of kiwi. So I want 6,7,8. In this case.

Bruteforce search loop:

 $searchObject = "kiwi";
 $keys = array();
 foreach($array as $k => $v) {
 if($v == $searchObject) $keys[] = $k; 
}

3 Answers 3

47

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

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

Would yield something like this:

Array
(
    [0] => 6
    [1] => 7
    [2] => 8
)

Sample Output

Sign up to request clarification or add additional context in comments.

Comments

2
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));

Comments

0

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.",";
        }
    }
?>

1 Comment

is that quicker solution? i dont think so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.