1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for putting it in detail mate.
1

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.

2 Comments

+1 Barmar. You described it first.
Thanx, as Shankar Damodaran mentioned you described it first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.