Page 1 of 1

return an index of an associative array

Posted: Mon Jan 16, 2012 10:24 am
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

Re: return an index of an associative array

Posted: Mon Jan 16, 2012 10:49 am
by pickle

Code: Select all

foreach($myArray as $index=>$value){
    echo $index;
}

Re: return an index of an associative array

Posted: Mon Jan 16, 2012 11:21 am
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

Re: return an index of an associative array

Posted: Mon Jan 16, 2012 11:37 am
by robasc33
Thanks everyone, much appreciated