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

What is the usage of foreach in php

王林
Release: 2023-03-07 12:40:02
Original
7023 people have browsed it

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) {
	要执行代码;
}
Copy after login

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) {
	要执行代码;
}
Copy after login

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;
}
?>
Copy after login

Example:

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

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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template