search
HomeBackend DevelopmentPHP Tutorial当我们使用foreach时,内部究竟发生了什么(PHP5)?

以下所有结论均基于PHP5版本

看下面一段最基础的foreach遍历数组代码。

<?php $arr = array(‘a’,’b’,’c’);foreach ($arr as $key=> $value) {    echo $key,$value,’<br/>’; //output :  0a1b2c}?> 

输出为’0a1b2c’自然没有疑问,那么此过程中$arr,$key,$value究竟是经过怎样的运算,才输出这个结果的呢?

其实foreach遍历过程中,并不是直接操作$arr(原数组)的,而是会将$arr复制出一个$arrcopy(是一个$arr的一个复制品,我这里以$arrcopy代替),foreach在遍历过程中操作的其实一直是$arrcopy。

注:关于$arrcopy这个值我们是没办法提取出来的,因为这是我给他的命名,并没有存在这个变量,但是foreach遍历过程中确实会产生这么一个副本,这儿为了方便讲述我用$arrCopy代表。

Foreach遍历大概的流程是这样(伪代码):

<?php //伪代码$arr = array('a','b','c');/* foreach循环开始*///first loop$arrCopy = $arr; //复制出一个待循环数组的副本,接下来都是操作这个副本$key = currentKey($arrCopy); //将获取到的值分配给$k;$val = currentVal($arrCopy); //将获取到的值分配给$v;next($arrCopy);//移动副本数组的指针$arr = $arrCopy;//将副本赋值回给$arr((主要是将指针同步移动))//大括号内容{    echo $key,$value,’<br/>’;}//firt loop end//second loop $key = currentKey($arrCopy); //将获取到的值分配给$k;$val = currentVal($arrCopy); //将获取到的值分配给$v;………//seconde loop end?>

这就是foreach代码的运行流程,总结一句话就是foreach遍历操作的时候并不是原始数组,而是一个拷贝数组,但是每次循环的结尾都会将副本重新赋值回给原数组$arr = $arrCopy;。

如何证明我的说法呢?可以用下面这段代码检验。

<?php // $a = array('a','b','c'); $arr = array('a','b','c');foreach ($arr as $key=> $value) {    $arr[] = 'd';    print_r($arr);    var_dump($key,$value);}?>

输出结果为:

//output:Array    (    [0] => a    [1] => b    [2] => c    [3] => d    )    int(0)    string(1) "a"    Array    (    [0] => a    [1] => b    [2] => c    [3] => d    [4] => d    )    int(1)    string(1) "b"    Array    (    [0] => a    [1] => b    [2] => c    [3] => d    [4] => d    [5] => d    )    int(2)    string(1) "c"

同学们看出来了吗?

$arr数组的键值对一直在在增加,可是$key,$value的值到了int(2),string(1) “c”就结束了,并没有如我们所料的将值为d的那些键值对打印出来。

这儿就能证明,foreach遍历过程操作的是$arr的副本($arrcopy)。

对了,foreach使用过程中还有一些小地方需要注意。例如foreach遍历数组的指针问题:

 <?php $arr = array('a','b','c');var_dump(current($arr)); //output:string(1) "a"foreach ($arr as $key=> $value) {}var_dump(current($arr)); //output:bool(false)?>

两次输出,不一样的结果。为什么呢?因为foreach循环遍历后的数组,该数组的指针是指向末尾的(此处的话指针就是在’c’的右边),并且使用完毕后不会帮我们复位,所以我们var_dump(current($arr))为 bool(false)。那么在这里我们需要特别注意,为了保险起见我们在foreach遍历数组后,最好手动reset()一下数组,防止出错:

<?php $arr = array('a','b','c');var_dump(current($arr)); //output:string(1) "a"foreach ($arr as $key=> $value) {}reset($arr);var_dump(current($arr)); / output:string(1) "a"?>

这样就正常了。

还有一点PHP手册也提醒我们了:

转成代码的意思就是:

<?php $arr = array('a','b','c');foreach ($arr as $key=> $value) {}var_dump($key);var_dump($value);?>

Foreach遍历后,$key和$value是真实存在的,最好使用后能手动unset()掉。

总结:foreach算是PHP里面比较复杂的一个函数了,因为牵扯到PHP底层的C语言的结构体,引用(is_ref__gc),指针移动……,所以在使用foreach的时候一定要特别注意啊!

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor