/    Sign up×
Community /Pin to ProfileBookmark

hi guys, try as i may i can’t seem to wrap my head around array keys.

i have an array of categories listed on no particular order.

i use asort() to get them into alphabetical order, and now
i need to loop through the array and print each one as a clickable
link with the corresponding key.

i tried using key(), with a regular ‘for loop’ but the same key is being
printed for every element of the array.

here’s my code…

asort($data); //name of array is $data

for( $i = 0; $i < sizeof($data); $i++ ){
echo “<li>$data[$i] ” . key($data);
}

how can i correct it to get the proper key?

thanks,
Michael.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@toenailsinFeb 13.2009 — you need to advance the arrays internal pointer

[CODE]for( $i = 0; $i < sizeof($data); $i++ ){
echo "<li>$data[$i] " . key($data);
next($data);
}[/CODE]
Copy linkTweet thisAlerts:
@MindzaiFeb 13.2009 — Or use foreach which was designed for this very task and is much more efficient than calling sizeof every iteration:

[code=php]
foreach ($data as $key => $value) {
echo "<li>$value $key</li>";
}
[/code]
Copy linkTweet thisAlerts:
@bsmbahamasauthorFeb 13.2009 — i remember using the => operator before but

couldn't rememebr how, to structure it.

that did it,

thanks much.

Or use foreach which was designed for this very task and is much more efficient than calling sizeof every iteration:

[code=php]
foreach ($data as $key => $value) {
echo "<li>$value $key</li>";
}
[/code]
[/QUOTE]
×

Success!

Help @bsmbahamas spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...