What does the =>
operator mean in the following code?
foreach ($user_list as $user => $pass)
The code is a comment at PHP.net.
The user does not specify the value of $user_list
, $user
or $pass.
I normally see that =>
means equal or greater than.
However, I am not sure about its purpose here because it is not assigned.
I read the code as
- process a list of users in integers
- such that the value of each user is equal or greater than password
The above does not make sense to me.
Answer
=>
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
.
Example:
$user_list = array(
'dave' => 'apassword',
'steve' => 'secr3t'
);
foreach ($user_list as $user => $pass) {
echo "{$user}'s pass is: {$pass}\n";
}
// Prints:
// "dave's pass is: apassword"
// "steve's pass is: secr3t"
Note that this can be used for numerically indexed arrays too.
Example:
$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw
No comments:
Post a Comment