Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'as' operator in PHP

Tags:

operators

php

In PHP, what does the operator 'as' do? For example,

foreach ( $this->Example as $Example )

Thanks.

like image 590
Randomblue Avatar asked Apr 19 '11 17:04

Randomblue


People also ask

What is the => operator in PHP?

=> 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.

What is === in PHP?

=== 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.


3 Answers

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.

like image 101
Shoe Avatar answered Sep 22 '22 15:09

Shoe


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

like image 38
Mike Lewis Avatar answered Sep 20 '22 15:09

Mike Lewis


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.

like image 20
cprn Avatar answered Sep 24 '22 15:09

cprn