[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 8352
  • Last Modified:

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() ?
0
mnb93
Asked:
mnb93
  • 2
1 Solution
 
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now