/    Sign up×
Community /Pin to ProfileBookmark

There are two different ways to code a foreach loop:

[code=php]foreach (array_expression as $value) {}[/code]

[code=php]foreach (array_expression as $key => $value) {}[/code]

What exactly is the difference? If there is a difference, which one is better/used more?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@ZnupiJul 19.2008 — It depends on what you exactly want. When using the
[code=php]foreach (array_expression as $value) {}[/code]
form, you only get the value of each item in the array. When using the
[code=php]foreach (array_expression as $key => $value) {}[/code]
form, on the other hand, you also get the key name. That's useful when you have an associative array, and you don't know the exact keys:
[code=php]
$array = Array (
"someKey" => "someValue",
"anotherKey" => "anotherValue"
);
foreach ($array as $value) echo $value; // you only get the values, "someValue anotherValue";
foreach ($array as $key => $value) echo $key . ': ' . $value . ' / '; // You also get the keys -- "someKey: someValue / anotherKey: anotherValue"
[/code]

Hope that helps ?
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJul 19.2008 — But what exactly is the benefit of getting the keys? How does that help anything?
Copy linkTweet thisAlerts:
@ZnupiJul 19.2008 — Maybe you don't know what the keys are. Maybe they've been set dynamically. When you'll have to use it you'll see the benefit ?
×

Success!

Help @Joseph_Witchard 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.18,
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,
)...