Home > Article > Backend Development > Detailed example of the usage of foreach in php
1. What is foreach?
foreach is a grammatical structure of PHP. It is actually a tool (tool: a tool used when working). In the process of program development, in order to achieve program effects, use Arrived foreach.
2. How to use?
Official:
foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement
Example:
$arr = array(1,2,3,4);//定义数组 foreach ($arr as &$value) { $value = $value*2;//循环遍历并修改数组中的值 } echo "<pre class="brush:php;toolbar:false">"; print_r($arr);//打印输出最终结果
Result: (&$value is a reference assignment)
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
Example:
$a = array( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "<pre class="brush:php;toolbar:false">"; echo "[$k] => $v\n"; }
Result:
[one] => 1 [two] => 2 [three] => 3 [seventeen] => 17
Explanation: k actually refers to key, v actually refers to value
Summary: foreach is frequently used in PHP projects, especially when processing Array time!
For more related questions, please visit the PHP Chinese website: PHP Video Tutorial
The above is the detailed content of Detailed example of the usage of foreach in php. For more information, please follow other related articles on the PHP Chinese website!