


Traversing an array is the most common thing in programming. Here we discuss the two methods of for and foreach:
First, we prepare two arrays for traversal:
$arr1=array(1=>'a', 3=>22, 5=>'b', 4=>'c', 8=>'d'); $arr2=array('a'=>'aaa', 'b'=>'bbb', 'c'=>'ccc', 'd'=>'ddd', 'e'=>'eee');
1: for loop structure
Loop 1:
for($i=0,$num=count($arr1);$i<$num;$i++){ echo $arr1[$i].' '; }
Output result: a 22 c
Loop 2:
for($i=0,$num=count($arr2);$i<$num;$i++){ echo $arr2[$i].' '; }
This statement has no output
Analysis:
Loop 1 only prints out the first two units of array $arr1, while $arr2 in loop 2 prints nothing.
The reason is that the for loop increments according to the number, so for can only access the index array. For example, loop 1 incrementally accesses the $arr1 array from $i=0 to $i=4. The keys in the $arr1 array are from 0 to 4 cells, but the keys in the array are: 1,3,5,4,8. Array units with key values exceeding 4 (5=>'b',8=>'d') will not be accessed, because count($arr1)=5, so $i
2: foreach loop structure
Loop 3:
foreach($arr1 as $key=>$value){ echo $key.'=>'.$value.' '; }
Output result:
1=>a 3=>22 5=>b 4=>c 8=>d
Loop 4:
foreach($arr2 as $key=>$value){ echo $key.'=>'.$value.' '; }
Output result:
a=>aaa b=>bbb c=>ccc d=>ddd e=>eee
Analysis:
The foreach loop structure loops according to the pointer inside the array. When foreach starts to execute, the pointer inside the array will automatically point to the first unit. Therefore, the next unit will be obtained in the next loop, and there is no need to traverse the entire array according to the array key. This is also the difference between foreach and for. Of course, foreach can only be used with arrays and objects, and since foreach relies on an internal array pointer, modifying its value in a loop will likely lead to unexpected behavior.
Note: Each loop of for operates on the value under the corresponding index, and changes to each value will also be reflected in the traversed object. Each time foreach operates a unit, it takes its index and value into variables respectively, or only takes out the value into one variable, and then operates the variables with the index and value separately, without affecting the traversed object itself. . If you want to modify the value in the object during the traversal process, you need to add an & symbol before the variable in the declaration. For example: foreach($array as &$value).
Conclusion: If an array uses consecutive numbers as the keys of the array units, then you can use a for loop structure. If you are not sure whether the keys of the array or the keys of the array contain characters, you should use the foreach loop structure.
The above is the detailed content of Detailed explanation of the difference between for and foreach traversing arrays in php. For more information, please follow other related articles on the PHP Chinese website!

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

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

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
