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; }
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With