AkisC
AkisC

Reputation: 827

php array get positions of the specific value

I have one array and I want to get the positions of one specific value

Example:

$my_array = array(0,2,5,3,7,4,5,2,1,6,9);

My search is Number 5 the positions of Number 5 in array was (2 and 6)

If i call the array_search function, always returns the first position in array witch is 2.

Is there anyway to get the two ore more positions of specific value?

Upvotes: 3

Views: 8971

Answers (4)

Sumit Neema
Sumit Neema

Reputation: 480

  $result = array();
  foreach ($array as $key => $value)
   {
      $result[$value] =implode(',',array_keys($array,$value))

  }
  echo '<pre>';
print_r($result);

it will give you an array with values as key and their occurrences as values separated by comma

Upvotes: 1

Sergi Juanola
Sergi Juanola

Reputation: 6647

Have a look at array_keys second parameter. You can get the keys only matching $search_value

Upvotes: 2

christian.thomas
christian.thomas

Reputation: 1122

Use array_keys with the optional search parameter, that should return all of the keys.

$matches = array_keys($my_array, 5);

Upvotes: 12

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91902

Just loop over the array:

/* Searches $haystack for $needle.
   Returns an array of keys for $needle if found,
   otherwise an empty array */
function array_multi_search($needle, $haystack) {
  $result = array();
  foreach ($haystack as $key => $value)
    if ($value === $needle)
      $result[] = $key;
  return $result;
}

Upvotes: 1

Related Questions