Home > Backend Development > PHP Tutorial > How Does the `=>` Operator Function in PHP's `foreach` Loop?

How Does the `=>` Operator Function in PHP's `foreach` Loop?

Barbara Streisand
Release: 2024-12-05 17:44:10
Original
533 people have browsed it

How Does the `=>` Operator Function in PHP's `foreach` Loop?
` Operator Function in PHP's `foreach` Loop? " />

Operator Assignment in PHP foreach Loop

PHP features the => operator, commonly known for its implication of being equal or greater than. However, in the context of a foreach loop, its usage deviates from this conventional meaning.

Associative Array Separator

The => operator is employed as a separator for associative arrays. Within a foreach loop, it acts to assign the array's key to a specified variable ($user in this instance) and the corresponding value to another ($pass).

Example: Associative Array Iteration

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

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

Output:

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

Numeric Array Iteration

Remarkably, the => operator can also be employed with numerically indexed arrays.

Example: Numeric Array Iteration

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

Output:

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

Hence, within PHP's foreach loop, the => operator serves a distinct purpose as an associative array separator, enabling the traversal and access of key-value pairs.

The above is the detailed content of How Does the `=>` Operator Function in PHP's `foreach` Loop?. 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