return an index of an associative array

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
robasc33
Forum Newbie
Posts: 3
Joined: Tue Nov 15, 2011 12:03 pm

return an index of an associative array

Post by robasc33 »

Hello all,

I am trying to find a way to loop through an associative array in order to return the index of each item in the array, for instance if I have the data(as returned from var_dump):

[text]
array
1 => string 'FIRST ITEM' (length=16)
112 => string 'SECOND ITEM' (length=19)
[/text]

I want to loop through the array and output the index of each item

so if I loop through the array my output should display 1, 112

I tried key($array) but this returns null. I am assuming this is looking for a string value

Thanks
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: return an index of an associative array

Post by pickle »

Code: Select all

foreach($myArray as $index=>$value){
    echo $index;
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: return an index of an associative array

Post by twinedev »

You can also do:

Code: Select all

$aryKeys = array_keys($myArray);
echo implode(',',$aryKeys);
that would output something like:

Code: Select all

1,112
see http://php.net/array_keys for more info.

-Greg
robasc33
Forum Newbie
Posts: 3
Joined: Tue Nov 15, 2011 12:03 pm

Re: return an index of an associative array

Post by robasc33 »

Thanks everyone, much appreciated
Post Reply