Return numerical position of array element

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Return numerical position of array element

Post 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 :-)
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

returns the key if found..
mixed array_search( mixed needle, array haystack [, bool strict])

could be used in combination with array_keys();
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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 :-)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

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