Page 1 of 1

Return numerical position of array element

Posted: Sun Apr 18, 2004 8:30 am
by Chris Corbyn
Hi,

How can I return the numerical position of an array element even if I have already assigned key values to all of the element?

For example if I've got this array:

Code: Select all

$somearray = array ("Blue" => Bluefile.mid", "red" => "redfile.mid", "green" => "greenfile.mid", "orange" => "orangefile.mid" );
And I want to know that "green" is at key position [2] in the array is there a function that will do this?

Looked in the manual but I couldn't find anything except long-winded workarounds that would only work in the specific case I need to do this for.

Any hints?

Thanks :-)

Posted: Sun Apr 18, 2004 8:52 am
by JAM
Never thought of this... The only thing that comes into mind is:

Code: Select all

while ($key = key($somearray)) {
        if ($key == "green") { 
            echo $i;
        }
        $i++;
        next($somearray);
    }
Untested, should work though...
If someone have a better way, please do post.

Posted: Sun Apr 18, 2004 9:07 am
by feyd
returns the key if found..
mixed array_search( mixed needle, array haystack [, bool strict])

could be used in combination with array_keys();

Posted: Sun Apr 18, 2004 9:14 am
by Chris Corbyn
JAM's idea worked a treat.

Not quite sure what feyd is agetting at with array_search() but I'll have a look at that too.

Thanks guys :-)

Posted: Sun Apr 18, 2004 9:19 am
by feyd

Code: Select all

if(array_search('green',array_keys($somearray))==2)