Home >Backend Development >PHP Problem >What is the meaning of foreach as in php

What is the meaning of foreach as in php

WBOY
WBOYOriginal
2022-02-11 15:22:304351browse

In PHP, "foreach as" is a loop statement used to traverse an array. The syntax is "foreach($array as $value){to execute code;}". Each time the loop is performed, the current array The value of the element will be assigned to the $value variable.

What is the meaning of foreach as in php

The operating environment of this tutorial: windows10 system, PHP7.1 version, DELL G3 computer

What is the meaning of foreach as in php

The foreach loop is used to traverse the array.

Syntax

foreach ($array as $value)
{
    要执行代码;
}

Every time you loop, the value of the current array element will be assigned to the $value variable (the array pointer will move one by one). When you loop next time, you will See the next value in the array.

foreach ($array as $key => $value)
{
    要执行代码;
}

Every time you loop, the keys and values ​​of the current array elements will be assigned to the $key and $value variables (the numeric pointers will move one by one). When you perform the next loop, you will see the array. The next key and value in .

Example

The following example demonstrates a loop that outputs the values ​​of a given array:

Example

<?php
$x=array("Google","Runoob","Taobao");
foreach ($x as $value)
{
    echo $value . PHP_EOL;
}
?>

Output:

Google
Runoob
Taobao

The following example demonstrates a loop that outputs the keys and values ​​of a given array:

<?php
$x=array(1=>"Google", 2=>"Runoob", 3=>"Taobao");
foreach ($x as $key => $value)
{
    echo "key  为 " . $key . ",对应的 value 为 ". $value . PHP_EOL;
}
?>

Output:

key  为 1,对应的 value 为 Google
key  为 2,对应的 value 为 Runoob
key  为 3,对应的 value 为 Taobao

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the meaning of foreach as 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