1

there is an array like $arr = array(1,2,3,3,3,4,5) . What if we want to get all indexes that have values 3?

i used array_search(3, $arr) but it just give back an integer and just the first index that has value '3'

how can we get an array like $indexes = array(2,3,4) that shows all indexes that have value 3?

your help will be highly appreciated

TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
  • A Foreach loop ? – nice_dev Apr 14 '20 at 11:45
  • you surely have to code some kind of loop here. What have you tried so far ? – Pierre Apr 14 '20 at 11:46
  • This is actually explained in the [`array_search` manual page](https://www.php.net/manual/en/function.array-search.php#function.array-search.returnvalues) - *If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.* – iainn Apr 14 '20 at 12:00

3 Answers3

3

You can use array_keys with search value PHP Doc

Demo

array_keys($arr,3)

array_keys() returns the keys, numeric and string, from the array.

If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

LF00
  • 27,015
  • 29
  • 156
  • 295
1

With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped.

$a = [1,2,3,4,3,3,5,6];

$threes = array_filter($a, function($v, $k) {
  return $v === 3 ? $k : false; },
  ARRAY_FILTER_USE_BOTH
);

$threes Is an array containing all keys having the value 3.

array(3) { 2, 4, 5 }

Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
1

you can use array_keys:

foreach (array_keys($arr) as $key) if ($arr[$key] == 3) $result[] = $key;