$value)"."/> $value)".">
search
HomeBackend DevelopmentPHP ProblemDetailed explanation of the usage of php foreach

php Usage of foreach: 1. Use it through the syntax "foreach (array_expression as $value)"; 2. Use it through the syntax "foreach (array_expression as $key => $value)".

Detailed explanation of the usage of php foreach

Recommended: "PHP Video Tutorial"

Usage and examples of foreach in PHP

Foreach is often used in PHP, and to use foreach, you must use an array. Therefore, in this article, we will talk about arrays and foreach at the same time.

Foreach has two syntaxes:

The first one: traverse the given array statement array_expression array. Each time through the loop, the value of the current cell is assigned to $value and the pointer inside the array is moved forward one step (so the next cell will be obtained in the next loop).

foreach (array_expression as $value)

Second type: Same as above, at the same time, the key name of the current unit will also be assigned to the variable $key in each loop.

foreach (array_expression as $key => $value)

Let’s explain them one by one!

1. One-dimensional ordinary array and foreach

We first write a one-dimensional array, as follows:

$a = array('Tom','Mary','Peter','Jack');

1. We use the first one foreach method to output.

foreach ($a as $value) {
  echo $value."<br/>";
}

The final result is:

Tom
Mary
Peter
Jack

2. We use the second foreach method to output.

foreach ($a as $key => $value) {
  echo $key.&#39;,&#39;.$value."<br/>";
}

The final result is:

0,Tom
1,Mary
2,Peter
3,Jack

Summary: Obviously, we see that there is only one more $key, and the value of this $key is the serial number 1 , 2, 3, 4 and so on!

2. One-dimensional associative array and foreach

The one-dimensional associative array is as follows:

$b = array(&#39;a&#39;=>&#39;Tom&#39;,&#39;b&#39;=>&#39;Mary&#39;,&#39;c&#39;=>&#39;Peter&#39;,&#39;d&#39;=>&#39;Jack&#39;);

Some people also like to write it like this, as follows:

$b = array(
  &#39;a&#39;=>&#39;Tom&#39;,
  &#39;b&#39;=>&#39;Mary&#39;,
  &#39;c&#39;=>&#39;Peter&#39;,
  &#39;d&#39;=>&#39;Jack&#39;
);

1. We use the first foreach method to output the same as above.

foreach ($b as $value) {
  echo $value."<br/>";
}

The final result is:

Tom
Mary
Peter
Jack

2. We use the second foreach method to output.

foreach ($b as $key => $value) {
  echo $key.&#39;,&#39;.$value."<br/>";
}

The final result is:

a,Tom
b,Mary
c,Peter
d,Jack

Summary: Obviously, in a one-dimensional associative array, $key is the associated serial number, that is, the corresponding a, b, c, d.

3. Two-dimensional ordinary array and foreach

When traversing a two-dimensional array, it is a little more troublesome. Why? Because the traversed value is an array. Since it is an array, you can perform various operations on the array!

Let’s first look at a basic two-dimensional array, as follows:

$c = array(
  array(&#39;1&#39;,&#39;Tom&#39;),
  array(&#39;2&#39;,&#39;Mary&#39;),
  array(&#39;3&#39;,&#39;Peter&#39;),
  array(&#39;4&#39;,&#39;Jack&#39;)
);

1. We use the first foreach method:

foreach ($c as $value) {
  print_r($value);
  echo "<br/>";
}

gets the following result:

Array ( [0] => 11 [1] => Tom )
Array ( [0] => 22 [1] => Mary )
Array ( [0] => 33 [1] => Peter )
Array ( [0] => 44 [1] => Jack )

2. We use the second foreach method:

foreach ($c as $key => $value) {
  echo &#39;$key=&#39;.$key."<br/>";
  print_r($value);
  echo "<br/>";
}

gets the following result:

$key=0
Array ( [0] => 11 [1] => Tom )
$key=1
Array ( [0] => 22 [1] => Mary )
$key=2
Array ( [0] => 33 [1] => Peter )
$key=3
Array ( [0] => 44 [1] => Jack )

Summary: As can be seen from the above, for a basic two-dimensional array, $key is the serial number, such as 0\1\2\3 and so on!

4. Associative two-dimensional arrays and foreach

Explain that associative two-dimensional arrays are used a lot in actual projects. Why? Generally, the data extracted from the database is associated with two-dimensional arrays. If you learn to associate two-dimensional arrays, you will have mastered a large part of it in actual PHP practice!

Then first list the associated two-dimensional array, as follows:

$d = array(
  array(&#39;id&#39;=>&#39;11&#39;,&#39;name&#39;=>&#39;Tom&#39;),
  array(&#39;id&#39;=>&#39;22&#39;,&#39;name&#39;=>&#39;Mary&#39;),
  array(&#39;id&#39;=>&#39;33&#39;,&#39;name&#39;=>&#39;Peter&#39;),
  array(&#39;id&#39;=>&#39;44&#39;,&#39;name&#39;=>&#39;Jack&#39;)
);

1. Use the first method code:

foreach ($d as $value) {
  print_r($value);
  echo "<br/>";
}

The results obtained are as follows:

Array ( [id] => 11 [name] => Tom )
Array ( [id] => 22 [name] => Mary )
Array ( [id] => 33 [name] => Peter )
Array ( [id] => 44 [name] => Jack )

Obviously, the difference between association and non-association is: non-association is preceded by 0/1, etc., while association displays the specific name id/name, etc.

2. Code using the second method:

foreach ($d as $key => $value) {
  echo &#39;$key=&#39;.$key."<br/>";
  print_r($value);
  echo "<br/>";
}

The results obtained are as follows:

$key=0
Array ( [id] => 11 [name] => Tom )
$key=1
Array ( [id] => 22 [name] => Mary )
$key=2
Array ( [id] => 33 [name] => Peter )
$key=3
Array ( [id] => 44 [name] => Jack )

Summary: $key here is still 0/ 1/2/3.

5. Practical application in the project

Explanation: In the project, there are many changes in the array, of course foreach plays an important role! Of course, you can also use while, each, etc. methods, but foreach is the most convenient! Let’s briefly talk about some common project practices!

Practical 1: Convert a two-dimensional associative array into a one-dimensional ordinary array

Still the fourth list of associative two-dimensional arrays, as follows:

$d = array(
  array(&#39;id&#39;=>&#39;11&#39;,&#39;name&#39;=>&#39;Tom&#39;),
  array(&#39;id&#39;=>&#39;22&#39;,&#39;name&#39;=>&#39;Mary&#39;),
  array(&#39;id&#39;=>&#39;33&#39;,&#39;name&#39;=>&#39;Peter&#39;),
  array(&#39;id&#39;=>&#39;44&#39;,&#39;name&#39;=>&#39;Jack&#39;)
);

Now we only need one column: name Of course, we can use the following methods to implement it,

foreach ($d as $key => $value) {
  echo ($value[&#39;name&#39;]);
  echo "<br/>";
}

But sometimes we have to list it as a one-dimensional array, so we have the following method:

//获取name列作为一维数组
$nameArr = array(); //name列
foreach ($d as $key => $value) {
  $nameArr[] = $value[&#39;name&#39;];
}
print_r($nameArr);

Above, by assigning an empty array value, foreach this empty array is equal to our value, and we get a new array! The result of the above code is as follows:

Array
(
  [0] => Tom
  [1] => Mary
  [2] => Peter
  [3] => Jack
)

This array is obviously: a one-dimensional ordinary array, as follows:

$d = array(&#39;Tom&#39;,&#39;Mary&#39;,&#39;Peter&#39;,&#39;Jack&#39;);

Okay, let’s convert the two-dimensional That’s all for turning an associative array into a one-dimensional ordinary array!

Practice 2: Two-level classification and infinite-level classification

Obviously, the data we take out from the database is a two-dimensional array, and it is a two-dimensional associative array. So, how do we extract the parent category? How to get out the subcategories corresponding to the parent category?

The first thing to explain is: almost all categories are a database schema, so it is very necessary for us to understand its structure and how to retrieve the corresponding data!

For the second-level classification, for the convenience of explanation, I found a better example from the Internet, that is "news classification"!

Okay, without further ado, let’s get down to business! Let's write an array first.

//从数据库中取出的分类数据
$original_array = array(
  array(&#39;id&#39; => 1,&#39;pid&#39; => 0,&#39;name&#39; => &#39;新闻分类&#39;),
  array(&#39;id&#39; => 2,&#39;pid&#39; => 0,&#39;name&#39; => &#39;最新公告&#39;),
  array(&#39;id&#39; => 3,&#39;pid&#39; => 1,&#39;name&#39; => &#39;国内新闻&#39;),
  array(&#39;id&#39; => 4,&#39;pid&#39; => 1,&#39;name&#39; => &#39;国际新闻&#39;),
  array(&#39;id&#39; => 5,&#39;pid&#39; => 0,&#39;name&#39; => &#39;图片分类&#39;),
  array(&#39;id&#39; => 6,&#39;pid&#39; => 5,&#39;name&#39; => &#39;新闻图片&#39;),
  array(&#39;id&#39; => 7,&#39;pid&#39; => 5,&#39;name&#39; => &#39;其它图片&#39;)
);

At the same time, the database looks like this.

说明:数据库的分类就是这个样子的!取出来的数组也是这个样子的!一般这样子的!

//从数据库中取出的分类数据
$original_array = array(
  array(
    &#39;id&#39; => 1,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;新闻分类&#39;
  ),
  array(
    &#39;id&#39; => 2,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;最新公告&#39;
  ),
  array(
    &#39;id&#39; => 3,
    &#39;pid&#39; => 1,
    &#39;name&#39; => &#39;国内新闻&#39;
  ),
  array(
    &#39;id&#39; => 4,
    &#39;pid&#39; => 1,
    &#39;name&#39; => &#39;国际新闻&#39;
  ),
  array(
    &#39;id&#39; => 5,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;图片分类&#39;
  ),
  array(
    &#39;id&#39; => 6,
    &#39;pid&#39; => 5,
    &#39;name&#39; => &#39;新闻图片&#39;
  ),
  array(
    &#39;id&#39; => 7,
    &#39;pid&#39; => 5,
    &#39;name&#39; => &#39;其它图片&#39;
  )
);

那么首先我们得知道我们想要的结果是什么样子呢?这一点:我们必要知道!(以前我对这方面了解比较不深,又常用开源程序,因此导致我不怎么会写这方面了)

我们最终想要的结果是这样子的!(不怕大家笑话,这一点我请一个朋友帮的忙才解决的!)

 

//整理后的分类数据
$output_array = array(
  array(
    &#39;id&#39; => 1,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;新闻分类&#39;,
    &#39;children&#39; => array(
      array(
        &#39;id&#39; => 3,
        &#39;pid&#39; => 1,
        &#39;name&#39; => &#39;国内新闻&#39;
      ),
      array(
        &#39;id&#39; => 4,
        &#39;pid&#39; => 1,
        &#39;name&#39; => &#39;国际新闻&#39;
      ),
    ),
  ),
  array(
    &#39;id&#39; => 2,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;最新公告&#39;,
  ),
  array(
    &#39;id&#39; => 5,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;图片分类&#39;,
    &#39;children&#39; => array(
      array(
        &#39;id&#39; => 6,
        &#39;pid&#39; => 5,
        &#39;name&#39; => &#39;新闻图片&#39;
      ),
      array(
        &#39;id&#39; => 7,
        &#39;pid&#39; => 5,
        &#39;name&#39; => &#39;其它图片&#39;
      ),
    ),
  ),
);

很明显,这里数组多了一个字段,就是 children!

那么,怎么 从 $original_array 变为 $output_array呢?这里有我一个朋友做的函数,当然也用到 foreach!

函数如下:

 

//整理函数
/**
 * 生成无限级树算法
 * @author Baiyu 2014-04-01
 * @param array $arr        输入数组
 * @param number $pid        根级的pid
 * @param string $column_name    列名,id|pid父id的名字|children子数组的键名
 * @return array $ret
 */
function make_tree($arr, $pid = 0, $column_name = &#39;id|pid|children&#39;) {
  list($idname, $pidname, $cldname) = explode(&#39;|&#39;, $column_name);
  $ret = array();
  foreach ($arr as $k => $v) {
    if ($v [$pidname] == $pid) {
      $tmp = $arr [$k];
      unset($arr [$k]);
      $tmp [$cldname] = make_tree($arr, $v [$idname], $column_name);
      $ret [] = $tmp;
    }
  }
  return $ret;
}

那们怎么使用呢?

 

//整理函数的使用
$output_array = make_tree($original_array);

完整使用方法如下:

 

$output_array =make_tree($arr, 0, &#39;id|pid|children&#39;)

函数之后,我们这样调用就得到了一级分类与二级分类!

foreach ($output_array as $key => $value) {
  echo &#39;<h2 id="value-name">&#39;.$value[&#39;name&#39;].&#39;</h2>&#39;;
  foreach ($value[&#39;children&#39;] as $key => $value) {
    echo $value[&#39;name&#39;].&#39;,&#39;;
}

结果如下:

附:$output_array 这个数组,我们使用print_r,就可以得到如下的结果!

 

Array
(
  [0] => Array
    (
      [id] => 1
      [pid] => 0
      [name] => 新闻分类
      [children] => Array
        (
          [0] => Array
            (
              [id] => 3
              [pid] => 1
              [name] => 国内新闻
              [children] => Array
                (
                )
 
            )
 
          [1] => Array
            (
              [id] => 4
              [pid] => 1
              [name] => 国际新闻
              [children] => Array
                (
                )
 
            )
 
        )
 
    )
 
  [1] => Array
    (
      [id] => 2
      [pid] => 0
      [name] => 最新公告
      [children] => Array
        (
        )
 
    )
 
  [2] => Array
    (
      [id] => 5
      [pid] => 0
      [name] => 图片分类
      [children] => Array
        (
          [0] => Array
            (
              [id] => 6
              [pid] => 5
              [name] => 新闻图片
              [children] => Array
                (
                )
 
            )
 
          [1] => Array
            (
              [id] => 7
              [pid] => 5
              [name] => 其它图片
              [children] => Array
                (
                )
 
            )
 
        )
 
    )
 
)

The above is the detailed content of Detailed explanation of the usage of php foreach. 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version