Home  >  Article  >  Backend Development  >  What does foreach mean in php

What does foreach mean in php

下次还敢
下次还敢Original
2024-04-29 13:03:16394browse

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.

What does foreach mean in php

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:

  1. Change$key and $value are set to the first element of the array or object.
  2. Execute the loop body.
  3. Sets $key and $value to the next element.
  4. Repeat steps 2 and 3 until all elements have been traversed.

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!

Statement:
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