Get Key by Value? (Array)

Posted on 2006-03-25
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() ?
Question by:mnb93
    LVL 49

    Accepted Solution

    $key = array_search('d', $chars);

    Should return '3';

    LVL 15

    Expert Comment

    function getKeyByValue ($array, $value) {
        $results = array_keys($array, $value);
        return $results[0];
    LVL 15

    Expert Comment

    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.
    LVL 2

    Expert Comment

    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: :)

    Featured Post

    Live: Real-Time Solutions, Start Here

    Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

    Join & Write a Comment

    Both Easy and Powerful How easy is PHP? (  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
    Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
    The viewer will learn how to dynamically set the form action using jQuery.
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now