Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search value in php array and get all keys

Tags:

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;  } 
like image 730
user1097772 Avatar asked Jan 26 '15 03:01

user1097772


2 Answers

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

like image 80
Kevin Avatar answered Oct 19 '22 17:10

Kevin


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)); 
like image 32
Syed Uzair Jawed Avatar answered Oct 19 '22 18:10

Syed Uzair Jawed