In PHP, what does the operator 'as' do? For example,
foreach ( $this->Example as $Example )
Thanks.
=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass . Note that this can be used for numerically indexed arrays too.
=== It is equal to operator. It is an identical operator. It is used to check the equality of two operands. It is used to check the equality of both operands and their data type.
Let's take an example:
foreach ($array as $value) {}
This means
foreach element (of
$array
) defined as$value
...
In other words this means that the elements of the array will be retrieved inside the loop as
$value
.
Notice that you can specify also this syntax:
foreach ($array as $key => $value) {}
In both ways the vars $key
and $value
will exists inside the foreach
and will correspond to the 'current' element of the array.
On each iteration of the foreach loop, $Example
is assigned to the current element in the loop.
Just to expand on existing answers. There's more than one use of as
keyword. Besides the obvious:
foreach ($dictionary as $key => $value) {}
It's also used to alias imported resources:
<?php
namespace foo;
use Full\Class\Path as MyAlias;
new MyAlias();
Which is useful, e.g. as a shorthand for AVeryLongClassNameThatRendersYourCodeUnreadable
or to substitute an object with your implementation when extending third party code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With