0

Given this associative array:

$currencies = [
    'foo' => [
        'name' => 'EUR',
        'symbol' => '€'
    ],
    'bar' => [
        'name' => 'USD',
        'symbol' => '$'
    ],
    'baz' => [
        'name' => 'GBP',
        'symbol' => '£'
    ],
];

How can I search for a name and retrieve key in a concise manner? I.e. searching for EUR returns foo.

I could loop, but I'd prefer a shorter way, if it exists...

Thanks

TechWisdom
  • 3,960
  • 4
  • 33
  • 40
Ivan
  • 2,463
  • 6
  • 39
  • 51
  • 1
    All operations with arrays (except accessing by key) are done via loop. If you don't see the loop - it's hidden under the hood. – u_mulder May 18 '20 at 16:03

1 Answers1

0
function searchCurrencies($currencies, $name) {
  foreach($currencies as $k => $v) {
    if($v->name==$name)
      return $k;
  };
};
RatajS
  • 1,403
  • 1
  • 14
  • 22
  • 2
    Hi, just for you to know: when you answer a question try to post something more complete than just the code, maybe add a little explanation of what was the author's error and how you fixed it. I'm telling you this because your answer has been flagged for deletion in the "Low Quality Post" queue. You can edit your answer using the "Edit" button , or by clicking here: [edit] – Federico Grandi May 18 '20 at 17:08