Get Key by Value? (Array)

I have an array
lets say for this example:
      $chars[] = 'a';
      $chars[] = 'b';
      $chars[] = 'c';
      $chars[] = 'd';
      $chars[] = 'e';
      $chars[] = 'f';
      $chars[] = 'g';
      $chars[] = 'h';
      $chars[] = 'i';
      $chars[] = 'j';

echo getKeyByValue('d') ; // 3
echo getKeyByValue('a') ; // 0
echo getKeyByValue('j') ; // 9

How can I do the currently non-existant function getKeybyValue() ?
LVL 5
mnb93Asked:
Who is Participating?
 
RoonaanCommented:
$key = array_search('d', $chars);

Should return '3';

-r-
0
 
TomeeboyCommented:
function getKeyByValue ($array, $value) {
    $results = array_keys($array, $value);
    return $results[0];
}
0
 
TomeeboyCommented:
Ah, I basically just remade array_search()  :)

If you want multiple results returned, array_keys() will return an array of keys that had values matching what you searched for.  If you just want the first one, then array_search should work fine.
0
 
WaielEidCommented:
it's the same as tomeeboy said
but if you want one arguemnt you have to globlize the array

function getKeyByValue ($value) {
    global $chars;
    $results = array_keys($chars, $value);
    return $results[0];
}

which is also array seach can do: :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.