Re: Simple array question

From: Date: Thu, 23 Oct 2003 00:34:11 +0000
Subject: Re: Simple array question
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-167202@lists.php.net to get a copy of this message
On Thu, 23 Oct 2003 14:01:59 -0500, you wrote: >Is there a simple way to return the key (name) of one element in an >array? I looked up key() in the docs, but there are no examples or >notes... Ok, to make sure I understand you: given an array ('apple' => 'red', 'banana' => 'yellow') you want a function where you submit 'red' and the function returns 'apple'? The problem is that keys have to be unique, but values don't. What should the function return for this array? ('apple' => 'red', 'banana' => 'yellow', 'tomato' => 'red') I can see two choices - if values are guaranteed unique, or if you only care about the last hit, use array_flip() to transform the array, then do a normal lookup: $a = array_flip ($a); $key = $a['red']; If you want /all/ the keys, just iterate over the array: $result = array(); $target = 'apple'; foreach ($a as $key => $val) { if ($target == $val) { $result[] = $key; } }

« previous php.general (#167202) next »