Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equals arrow operator in a foreach loop [duplicate]

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

like image 364
Steve O'Connor Avatar asked Dec 17 '22 08:12

Steve O'Connor


2 Answers

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);

like image 56
Daren Chandisingh Avatar answered Jan 09 '23 19:01

Daren Chandisingh


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;
like image 33
Brad Avatar answered Jan 09 '23 18:01

Brad