search
HomeBackend DevelopmentPHP TutorialHow to loop through arrays using foreach and for
How to loop through arrays using foreach and forJun 22, 2017 pm 03:04 PM
foreachcyclearrayconduct

The

foreach syntax structure is used to traverse the array.

foreach()

PHP foreach() syntax structure is used to traverse operations or output arrays. foreach() can only be used to traverse arrays or objects when trying to use it for other Data type or an uninitialized variable will generate an error.

Syntax:

foreach (array as $value)
    statement
// 或者:
foreach (array as $key => $value)
    statement

In the above syntax, each loop assigns the value of the current unit to $value and the pointer inside the array moves forward one step. In the second syntax format, the key name of the current unit is also assigned to the variable $key in each loop.

Example:

<?php
$arr_age = array("wang"=>18, "li"=>20, "zhang"=>25);
foreach ($arr_age as $age) {
    echo $age,&#39;<br />&#39;;
}
?>

Run this example output:

18
20
25

Use array key value

<?php
$arr_age = array("wang"=>18, "li"=>20, "zhang"=>25);
foreach ($arr_age as $key=>$age) {
    echo $key,&#39;: &#39;,$age,&#39;<br />&#39;;
}
?>

Run the example output:

wang: 18
li: 20
zhang: 25

Tips

When foreach starts executing, the pointer inside the array will automatically point to the first unit, which means there is no need to call reset() before the foreach loop.

foreach operates on a copy of the specified array, not the array itself. Modifications to the returned array elements will not affect the original array (see example below), but when the foreach loop runs to the end, the internal pointer of the original array will point to the end of the array.

<?php
$arr_age = array("wang"=>18, "li"=>20, "zhang"=>25);
foreach ($arr_age as $age) {
    $age = $age+10;
    echo $age,&#39;<br />&#39;;
}
// 输出原数组
print_r($arr_age);
?>

Output of running example:

28
30
35
Array ( [wang] => 18 [li] => 20 [zhang] => 25 )

To modify the original array elements in foreach, you can do it by reference. Change the above example to:

<?php
$arr_age = array("wang"=>18, "li"=>20, "zhang"=>25);
foreach ($arr_age as &$age) {
    $age = $age+10;
    echo $age,&#39;<br />&#39;;
}
// 输出原数组
print_r($arr_age);
?>

Output of running example :

18
20
25
Array ( [wang] => 28 [li] => 30 [zhang] => 35 )

Traverse Multidimensional array

The foreach syntax structure can only be used to traverse one-dimensional array. To traverse multidimensional arrays, generally use foreach Use nested recursion or split the original array into a one-dimensional array and then perform foreach traversal.

Two-dimensional array Mixed example:

$arr_age = array("wang"=>18, "li"=>20, "zhang"=>array("name"=>"小张", "age"=>25));
foreach ($arr_age as $age) {
    if(is_array($age)){
        foreach ( $age as $detail) {
        echo $detail,&#39;<br />&#39;;
        }
    } else {
        echo $age,&#39;<br />&#39;;
    }
}
?>

Run this example output:

18
20
小张
25

Traversal of multi-dimensional array The most appropriate processing method must be adopted based on the actual data structure.

Extended pre-reading

PHP arrays are implemented through HashTable tables, so foreach traverses the array according to the order in which elements are added. If you want to iterate by index size, you should use a for() loop.

for() loop to traverse the array

If you are operating an array of continuous key values, you can also use the for() loop to traverse the array:

<?php
$arr_age = array(18, 20, 25);
$num = count($arr_age);
for($i = 0; $i < $num; $i++){
    echo $arr_age[$i]."<br />";
}
?>

The output of the running example is as follows:

18
20
25

Tips

You can also use list() and each() to traverse the array, but the test found that it is not as efficient as foreach().

//使用array()语句结构将联系人列表中所有数据声明为一个二维数组,默认下标是顺序数字索引    
$contact1 = array(                                             //定义外层数组    
array(1,&#39;高某&#39;,&#39;A公司&#39;,&#39;北京市&#39;,&#39;(010)987654321&#39;,&#39;gm@Linux.com&#39;),//子数组1    
array(2,&#39;洛某&#39;,&#39;B公司&#39;,&#39;上海市&#39;,&#39;(021)123456789&#39;,&#39;lm@apache.com&#39;),//子数组2    
array(3,&#39;峰某&#39;,&#39;C公司&#39;,&#39;天津市&#39;,&#39;(022)24680246&#39;,&#39;fm@mysql.com&#39;),  //子数组3    
array(4,&#39;书某&#39;,&#39;D公司&#39;,&#39;重庆市&#39;,&#39;(023)13579135&#39;,&#39;sm@php.com&#39;)     //子数组4    
);   //以HTML表格的形式输出二维数组中的每个元素    
echo &#39;<table border="1" width="600" align="center">&#39;;    
echo &#39;<caption><h1 id="联系人列表">联系人列表</h1></caption>&#39;;    
echo &#39;<tr bgcolor="#dddddd">&#39;;    
echo &#39;<th>编号</th><th>姓名</th><th>公司</th><th>地址</th><th>电话</th><th>EMALL</th>&#39;;    
echo &#39;</tr>&#39;;    //使用双层for语句嵌套二维数组$contact1,以HTML表格的形式输出
    //使用外层循环遍历数组$contact1中的行    
    for($row=0;$row<count($contact1);$row++)
    {        echo &#39;<tr>&#39;;        //使用内层循环遍历数组$contact1 中 子数组的每个元素,使用count()函数控制循环次数        
        for($col=0;$col<count($contact1[$row]);$col++)
            {            
             echo &#39;<td>&#39;.$contact1[$row][$col].&#39;</td>&#39;;
            }        
         echo &#39;</tr>&#39;;
    }    
         echo &#39;</table>&#39;;
$contact1 = array(                   //定义外层数组
    array(1,&#39;高某&#39;,&#39;A公司&#39;,&#39;北京市&#39;,&#39;(010)987654321&#39;,&#39;gm@Linux.com&#39;),//子数组1
    array(2,&#39;洛某&#39;,&#39;B公司&#39;,&#39;上海市&#39;,&#39;(021)123456789&#39;,&#39;lm@apache.com&#39;),//子数组2
    array(3,&#39;峰某&#39;,&#39;C公司&#39;,&#39;天津市&#39;,&#39;(022)24680246&#39;,&#39;fm@mysql.com&#39;),  //子数组3
    array(4,&#39;书某&#39;,&#39;D公司&#39;,&#39;重庆市&#39;,&#39;(023)13579135&#39;,&#39;sm@php.com&#39;)     //子数组4
);
foreach($contact1 as $key=>$s){
//echo  $key;//以每个数组的键值作为表名
    foreach($s as $row){
    echo  $row;
    }
}

The above is the detailed content of How to loop through arrays using foreach and for. 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
Java ArrayList遍历时使用foreach和iterator删除元素的区别是什么?Java ArrayList遍历时使用foreach和iterator删除元素的区别是什么?Apr 27, 2023 pm 03:40 PM

一、Iterator和foreach的区别多态差别(foreach底层就是Iterator)Iterator是一个接口类型,他不关心集合或者数组的类型;for和foreach都需要先知道集合的类型,甚至是集合内元素的类型;1.为啥说foreach底层就是Iterator编写的代码:反编译代码:二、foreach与iterator时remove的区别先来看阿里java开发手册但1的时候不会报错,2的时候就会报错(java.util.ConcurrentModificationException)首

php如何判断foreach循环到第几个php如何判断foreach循环到第几个Jul 10, 2023 pm 02:18 PM

​php判断foreach循环到第几个的步骤:1、创建一个“$fruits”的数组;2、创建一个计数器变量“$counter”初始值为0;3、使用“foreach”循环遍历数组,并在循环体中增加计数器变量的值,再输出每个元素和它们的索引;4、在“foreach”循环体外输出计数器变量的值,以确认循环到了第几个元素。

PHP返回一个键值翻转后的数组PHP返回一个键值翻转后的数组Mar 21, 2024 pm 02:10 PM

这篇文章将为大家详细讲解有关PHP返回一个键值翻转后的数组,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。PHP键值翻转数组键值翻转是一种对数组进行的操作,它将数组中的键和值进行交换,生成一个新的数组,其中原始键作为值,原始值作为键。实现方法在php中,可以通过以下方法对数组进行键值翻转:array_flip()函数:array_flip()函数专门用于键值翻转操作。它接收一个数组作为参数,并返回一个新的数组,其中键和值已交换。$original_array=[

Go语言中的循环和递归的比较研究Go语言中的循环和递归的比较研究Jun 01, 2023 am 09:23 AM

注:本文以Go语言的角度来比较研究循环和递归。在编写程序时,经常会遇到需要对一系列数据或操作进行重复处理的情况。为了实现这一点,我们需要使用循环或递归。循环和递归都是常用的处理方式,但在实际应用中,它们各有优缺点,因此在选择使用哪种方法时需要考虑实际情况。本文将对Go语言中的循环和递归进行比较研究。一、循环循环是一种重复执行某段代码的机制。Go语言中主要有三

python中使用矢量化替换循环python中使用矢量化替换循环Apr 14, 2023 pm 07:07 PM

所有编程语言都离不开循环。因此,默认情况下,只要有重复操作,我们就会开始执行循环。但是当我们处理大量迭代(数百万/十亿行)时,使用循环是一种犯罪。您可能会被困几个小时,后来才意识到它行不通。这就是在python中实现矢量化变得非常关键的地方。什么是矢量化?矢量化是在数据集上实现(NumPy)数组操作的技术。在后台,它将操作一次性应用于数组或系列的所有元素(不同于一次操作一行的“for”循环)。接下来我们使用一些用例来演示什么是矢量化。求数字之和##使用循环importtimestart

5个必备的Python入门实例代码5个必备的Python入门实例代码Jan 13, 2024 am 08:39 AM

Python入门代码:学习必备的5个实例Python是一种简单易学的高级编程语言,广泛用于数据分析、机器学习、网络爬虫等领域。对于初学者来说,掌握一些基本的Python代码是很重要的。本文将介绍5个简单的实例代码,帮助初学者快速入门Python编程。打印Hello,World!print("Hello,World!")这是Python

如何处理PHP循环嵌套错误并生成相应的报错信息如何处理PHP循环嵌套错误并生成相应的报错信息Aug 07, 2023 pm 01:33 PM

如何处理PHP循环嵌套错误并生成相应的报错信息在开发中,我们经常会用到循环语句来处理重复的任务,比如遍历数组、处理数据库查询结果等。然而,在使用循环嵌套的过程中,有时候会遇到错误,如无限循环或者嵌套层数过多,这种问题会导致服务器性能下降甚至崩溃。为了更好地处理这类错误,并生成相应的报错信息,本文将介绍一些常见的处理方式,并给出相应的代码示例。一、使用计数器来

PHP返回数组中的当前元素PHP返回数组中的当前元素Mar 21, 2024 pm 12:36 PM

这篇文章将为大家详细讲解有关PHP返回数组中的当前元素,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。获取PHP数组中的当前元素php为访问和操作数组提供了多种方法,其中包括获取数组中的当前元素。以下介绍几种常用的技术:1.current()函数current()函数返回数组内部指针当前指向的元素。指针最初指向数组的第一个元素。使用以下语法:$currentElement=current($array);2.key()函数key()函数返回数组内部指针当前指向元

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment