user3247608
user3247608

Reputation: 593

how does foreach loop work php?

for example:

$numbers = array(1, 2, 3, 4, 5);

foreach($numbers as $value)
{
    echo $value;
}

what does as do, I assume it's a keyword because it is highlighted as one in my text editor. I checked the keyword list at http://www.php.net/manual/en/reserved.keywords.php and the as keyword was present. It linked to the foreach construct page, and from what I could tell didn't describe what the as keyword did. Does this as keyword have other uses or is it just used in the foreach construct?

Upvotes: 1

Views: 100

Answers (2)

Barmar
Barmar

Reputation: 780724

as is just part of the foreach syntax, it's used to specify the variables that are assigned during the iteration. I don't think it's used in any other context in PHP.

Upvotes: 1

Brandon - Free Palestine
Brandon - Free Palestine

Reputation: 16656

It's used to iterate over Iterators, e.g. arrays. It reads:

foreach value in $numbers, assign the value to $value.

You can also do:

foreach ($numbers as $index => $value) {

}

Which reads:

foreach value in $numbers, assign the index/key to $index and the value to $value.

To demonstrate the full syntax, lets say we have the following:

$array = array(
  0 => 'hello',
  1 => 'world')
);

For the first iteration of our foreach loop, $index would be 0 and $value would be 'hello'. For the second iteration of our foreach loop, $index would be 1, and $value would be 'world'.

Foreach loops are very common. You may have seen them as for..in loops in other languages.

For the as keyword, you're saying:

for each value in $numbers AS $value

It's a bit awkward, I know. As far as I know, the as keyword is only used with foreach loops.

Upvotes: 2

Related Questions