开发者

PHP equals arrow operator in a foreach loop [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What does $k => $v in foreach($ex as $k=>$v) mean?

I am trying to understand what this means:

foreach($this->domains as $domain=>$users) {  

// some code...

}

I understand $this->domains is an array that foreach will index over. But what does as $domain=>$users mean? I h开发者_开发百科ave only seen the => operator used in an array to set (key, value) pairs. The class has a member called $domain, but I assume that would be accessed as $this->domain.


The => operator specifies an association. So assuming $this->domains is an array, $domain will be the key, and $users will be the value.

<?php
$domains['example.com'] = 'user1';
$domains['fred.com'] = 'user2';

foreach ($domains as $domain => $user) {
    echo '$domain, $user\n';
}

Outputs:

example.com, user1
fred.com, user2

(In your example, $users is probably an array of users);


Think of it this way:

foreach($this->domains as $key=>$value) {

It will step through each element in the associative array returned by $this->domains as a key/value pair. The key will be in $domain and the value in $users.

To help you understand, you might put this line in your foreach loop:

echo $domain, " => ", $users;


Read foreach

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.


$domain here is a local variable that contains the key of the current item in the array. That is if your array is:

$ages = array("dad" => 31, "mom" => 35, "son" => 2);

Then

foreach($ages as $name=>$age) 
{  
   // prints dad is 32 years old, mom is 35 years old, etc
   echo "$name is $age years old"

}

In the loop body, referring to $name would refer to the current key, ie "dad", "mom" or "son". And $age would refer to the age we've stored above at the current key.

assume that would be accessed as $this->domain.

You're right, just $domain is the local variable here. You need $this->domain to get the member variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜