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

What is the usage of foreach in php

王林
王林Original
2020-11-06 11:23:227018browse

The usage of foreach in php is: [foreach ($array as $value) {To execute code;}], every time a loop is performed, the value of the current array element will be assigned to the $value variable. The next time you go through the loop, you get the next value in the array.

What is the usage of foreach in php

The foreach loop is used to traverse the array.

(Learning video recommendation: java course)

Grammar format:

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

Each time a loop is performed, the value of the current array element will be assigned Give the $value variable (the array pointer will move one by one), and the next time you loop through it, 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:

<?php
$x=array("Gooooo","Runrun","Taotao");
foreach ($x as $value) {
	echo $value . PHP_EOL;
}
?>

Example:

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

Related recommendations:php training

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