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;
    }
}

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to