What does "=>" mean in PHP?



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

  1. process a list of users in integers
  2. such that the value of each user is equal or greater than password

The above does not make sense to me.

10/9/2012 12:42:22 AM

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


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


$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
1/20/2015 11:40:10 AM

It means assign the key to $user and the variable to $pass

When you assign an array, you do it like this

$array = array("key" => "value");

It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

According to the PHP Manual, the '=>' created key/value pairs.

Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.

And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:

$array = array("test" => "foo");

foreach($array as $key => $value)
    echo $key . " : " . $value; // Echoes "test : foo"

foreach($array as $value)
    echo $value; // Echoes "foo"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow