We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Get Key by Value? (Array)

mnb93
mnb93 asked
on
Medium Priority
8,400 Views
Last Modified: 2008-01-09
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() ?
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2006
Commented:
$key = array_search('d', $chars);

Should return '3';

-r-

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT

Commented:
function getKeyByValue ($array, $value) {
    $results = array_keys($array, $value);
    return $results[0];
}
CERTIFIED EXPERT

Commented:
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.

Commented:
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: :)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.