/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] numerically iterating through an associative array

hi,

how do you numerically iterate through an associative array?

for instance:

[code=php]echo($_SERVER[0]); // knowing that key for the first “index” is something like “ALL_HTTP”[/code]

using the above code produces no output (or errors, at least on my server..)

the “why” is irrelevant. the question is can it be done?

PS- im fully aware of “foreach”. this is not my need or intention.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiMay 20.2009 — The 'why' is not really irrelevant; the reason it doesn't work is because there is no item in your array with a key of 0. If you turn error reporting on you'll see a notice level error about an undefined offset. If you don't want to use foreach for whatever reason, the easiest way is probably just:

[code=php]$server = array_values($_SERVER);
echo $server[0];
[/code]


However it seems a bit redundant when you already have foreach for iterating associative arrays.
Copy linkTweet thisAlerts:
@NogDogMay 20.2009 — Just a bit more info, PHP itself does not really care whether any given array key is an integer or a string: they are all still just arrays. foreach() will work identically with a string-indexed ("associative") array or an integer-indexed array. In fact, you can have both types of keys in the same array:
[code=php]
$myArray = array(
'zero' => 'value 1',
0 => 'value 2',
1 => 'value 3',
'one' => 'value 4'
);
echo $myArray[0]; // outputs "value 2"
[/code]

So outside of doing what Mindzai suggests with array_values(), I don't know how else to address your question.
Copy linkTweet thisAlerts:
@Angry_Black_ManauthorMay 20.2009 — thanks gentlemen. i assumed that you could still refer to an associative array by index in the same way you can in javascript. i appreciate the "array_values" clarification.
×

Success!

Help @Angry_Black_Man 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.19,
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,
)...