[ACCEPTED]-'as' operator in PHP-operators

Accepted answer
Score: 17

Let's take an example:

foreach ($array as $value) {}

This means

foreach 7 element (of $array) defined as $value...

In other words 6 this means that the elements of the array 5 will be retrieved inside the loop as $value. Notice 4 that you can specify also this syntax:

foreach ($array as $key => $value) {}

In 3 both ways the vars $key and $value will exists inside 2 the foreach and will correspond to the 'current' element 1 of the array.

Score: 3

On each iteration of the foreach loop, $Example is 1 assigned to the current element in the loop.

Score: 3

Just to expand on existing answers. There's 6 more than one use of as keyword. Besides the 5 obvious:

foreach ($dictionary as $key => $value) {}

It's also used to alias imported 4 resources:

<?php
namespace foo;
use Full\Class\Path as MyAlias;
new MyAlias();

Which is useful, e.g. as a shorthand 3 for AVeryLongClassNameThatRendersYourCodeUnreadable or to substitute an object with your 2 implementation when extending third party 1 code.

Score: 2

It's only used with foreach and it defines the 2 variable (or key/value variable pair) that 1 represents the current item in the array.

Score: 2

here is info from http://php.net/manual/en/control-structures.foreach.php

foreach (array_expression as $value)
    statement

The first form loops over 4 the array given by array_expression.

On 3 each loop, the value of the current element is assigned to $value and the internal array pointer 2 is advanced by one (so on the next loop, you'll 1 be looking at the next element).

Score: 0

Takes each entries in the array ie, $this->Example 1 and puts it in $Example

more details in http://php.net/manual/en/control-structures.foreach.php

Score: 0

It's used in a foreach construct to iterate through 6 an array. The code in the foreach block will be 5 run for each element in the array (in this 4 example, $this->Example). Every time it is run, the variable 3 after as (in this example, $Example) will be set to 2 the value of the current element in the 1 array.

More Related questions