Table of Contents
foreach()
Use array key value
Tips
Multidimensional array" >Traverse Multidimensional array
Extended pre-reading
for() loop to traverse the array
Home Backend Development PHP Tutorial How to loop through arrays using foreach and for

How to loop through arrays using foreach and for

Jun 22, 2017 pm 03:04 PM
foreach cycle array conduct

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

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,'<br />';
}
?>
Copy after login

Run this example output:

18
20
25
Copy after login
Copy after login

Use array key value

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

Run the example output:

wang: 18
li: 20
zhang: 25
Copy after login

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,'<br />';
}
// 输出原数组
print_r($arr_age);
?>
Copy after login

Output of running example:

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

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,'<br />';
}
// 输出原数组
print_r($arr_age);
?>
Copy after login

Output of running example :

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

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,'<br />';
        }
    } else {
        echo $age,'<br />';
    }
}
?>
Copy after login

Run this example output:

18
20
小张
25
Copy after login

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

The output of the running example is as follows:

18
20
25
Copy after login
Copy after login

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

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 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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

How to remove duplicate elements from PHP array using foreach loop?

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

PHP array key value flipping: Comparative performance analysis of different methods

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

PHP array multi-dimensional sorting practice: from simple to complex scenarios

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

Application of PHP array grouping function in data sorting

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods

What are the alternatives to recursive calls in Java functions? What are the alternatives to recursive calls in Java functions? May 05, 2024 am 10:42 AM

What are the alternatives to recursive calls in Java functions?

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

The role of PHP array grouping function in finding duplicate elements

See all articles