Home >Backend Development >PHP Tutorial >What does foreach mean in php
foreach is a loop statement in PHP used to iterate over the elements in an array or object. It traverses each element in order and performs a specific operation until all elements have been traversed.
The meaning of foreach in PHP
foreach is a loop statement in PHP used to iterate over an array or object. It allows you to iterate over each element in an array or object and perform specific operations.
Syntax
<code class="php">foreach ($array as $key => $value) { // 循环体 }</code>
Where:
$array
is the array or object to be traversed. $key
is the array key (if the array is an associative array) or the element index (if the array is an indexed array). $value
is the value of an array element or object property. How it works
When executing a foreach loop, PHP will:
$key
and $value
are set to the first element of the array or object. $key
and $value
to the next element. Example
Traverse an associative array:
<code class="php">$fruits = ['apple' => '红色', 'banana' => '黄色', 'orange' => '橙色']; foreach ($fruits as $fruit => $color) { echo "{$fruit} 的颜色是 {$color}。"; }</code>
Output:
<code>apple 的颜色是 红色。 banana 的颜色是 黄色。 orange 的颜色是 橙色。</code>
Traverse an object:
<code class="php">class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $person = new Person('John Doe', 30); foreach ($person as $property => $value) { echo "{$property}: {$value}"; }</code>
Output:
<code>name: John Doe age: 30</code>
The above is the detailed content of What does foreach mean in php. For more information, please follow other related articles on the PHP Chinese website!