3

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?

4 Answers 4

12

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

$matches = array_keys($my_array, 5);

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

2 Comments

Yes Thank you that is much better using array_keys thanks christian.thomas
what if array keys are changed.
2

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

Comments

1

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;
}

Comments

1
  $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

Comments

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.