Home > Backend Development > PHP Problem > Detailed example of the usage of foreach in php

Detailed example of the usage of foreach in php

王林
Release: 2023-02-23 15:18:02
Original
4764 people have browsed it

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
Copy after login

Example:

$arr = array(1,2,3,4);//定义数组
foreach ($arr as &$value) {
    $value = $value*2;//循环遍历并修改数组中的值
}
echo "<pre class="brush:php;toolbar:false">";
print_r($arr);//打印输出最终结果
Copy after login

Result: (&$value is a reference assignment)

  Array
  (
      [0] => 2
      [1] => 4
      [2] => 6
      [3] => 8
  )
Copy after login

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

Result:

[one] => 1
[two] => 2
[three] => 3
[seventeen] => 17
Copy after login

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!

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