Home > Backend Development > PHP Tutorial > How Does the `=>` Operator Work in PHP Associative Arrays?

How Does the `=>` Operator Work in PHP Associative Arrays?

Linda Hamilton
Release: 2024-12-04 22:56:15
Original
258 people have browsed it

How Does the `=>` Operator Work in PHP Associative Arrays?
` Operator Work in PHP Associative Arrays? " />

Understanding the "=>" Operator in PHP

In PHP, the "=>" operator plays a crucial role in working with associative arrays. It acts as a separator, allowing you to access both the key and value associated with each element in the array.

Consider the following code snippet:

foreach ($user_list as $user => $pass)
Copy after login

Here, the "=>" operator assigns the key of each array element to the variable $user and the corresponding value to the variable $pass.

For instance, given the following array:

$user_list = array(
    'dave' => 'apassword',
    'steve' => 'secr3t'
);
Copy after login

The code would execute the following loop:

foreach ($user_list as $user => $pass) {
    echo "{$user}'s pass is: {$pass}\n";
}
Copy after login

This loop would output:

dave's pass is: apassword
steve's pass is: secr3t
Copy after login

It's important to note that the "=>" operator can also be used with numerically indexed arrays, effectively mapping each index to a variable. For example:

$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
    echo "{$i}: {$type}\n";
}
Copy after login

This code would output:

0: car
1: truck
2: van
3: bike
4: rickshaw
Copy after login

The above is the detailed content of How Does the `=>` Operator Work in PHP Associative Arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template