Table of Contents
foreach引用引发的异常
在foreach后$v是否还存在
第二个循环分析
原因分析
Home Backend Development PHP Tutorial Exception handling after using & referencing foreach in php

Exception handling after using & referencing foreach in php

Mar 16, 2018 am 11:40 AM
foreach php abnormal

可能在PHP编码中使用&引用变量或者对象或者方法的人不多,但是&引用可以让你的代码变的简单而且节省资源消耗。在这篇文章中我们重点讨论的是foreach中使用&时出现的异常以及解决办法。

$exp = [
            [                'name' => 'test1',                'age' => 15,                'extension' => 'a:3:{s:4:"nose";s:4:"long";s:5:"mouth";s:3:"big";s:3:"eye";s:5:"small";}'
            ],
            [                'name' => 'test2',                'age' => 25,                'extension' => 'a:3:{s:4:"nose";s:5:"long2";s:5:"mouth";s:4:"big2";s:3:"eye";s:6:"small2";}'
            ],
            [                'name' => 'test4',                'age' => 18,                'extension' => 'a:3:{s:4:"nose";s:5:"long2";s:5:"mouth";s:4:"big2";s:3:"eye";s:6:"small2";}'
            ],
            [                'name' => 'test3',                'age' => 20,                'extension' => 'a:3:{s:4:"nose";s:5:"long3";s:5:"mouth";s:4:"big3";s:3:"eye";s:6:"small3";}'
            ],
        ];        foreach ($exp as &$v) {            $extension = @unserialize($v['extension']);            $v['nose'] = $extension['nose'] ?? "";            $v['mouth'] = $extension['mouth'] ?? "";            $v['eye'] = $extension['eye'] ?? "";
        }        $newExp = [];        foreach ($exp as $v) {            if ($v['mouth'] == "big3"){                $newExp[] = $v;
            }
        }
        dump($newExp);        exit;
Copy after login

这部分代码的功能描述如下:

1.将exp中的扩展字段混入到exp中2.如果exp中mouth为big3则赋值给新数组newExp3.输出newExp
Copy after login

从简单的表象来分析貌似以上逻辑并没有错,而且我们预测输出的结果应该为

...0 => array:6 [▼    "name" => "test3"
    "age" => 20
    "extension" => "a:3:{s:4:"nose";s:5:"long3";s:5:"mouth";s:4:"big3";s:3:"eye";s:6:"small3";}"
    "nose" => "long3"
    "mouth" => "big3"
    "eye" => "small3"
  ]
  ...
  但是结果并不是我们所预测的那样,程序输出的结果为:
  []
  这是为什么呢,我们来逐一分析
Copy after login

foreach引用引发的异常

第一个foreach是以下的代码块

foreach ($exp as &$v) {     $extension = @unserialize($v['extension']);     $v['nose'] = $extension['nose'] ?? "";     $v['mouth'] = $extension['mouth'] ?? "";     $v['eye'] = $extension['eye'] ?? "";
}
Copy after login

,在该代码块中使用了&v。因为我们这一步要做的事情是处理数组本身的数据所以使用引用对于内存消耗较少。在程序执行中

v应该就是exp最后一个元素的引用。
那么当我们修改$v的值应该exp的最后一个元素会变化。而且还有一个非常重要的问题就是foreach中使用了引用后引用在foreach结束后任然是存在的。也就是在以上的foreach之外$v依旧引用exp最后一个元素

在foreach后$v是否还存在

...foreach ($exp as &$v) {    $extension = @unserialize($v['extension']);    $v['nose'] = $extension['nose'] ?? "";    $v['mouth'] = $extension['mouth'] ?? "";    $v['eye'] = $extension['eye'] ?? "";
}  
dump($v);
输出结果为:array:6 [▼  "name" => "test3"
  "age" => 20
  "extension" => "a:3:{s:4:"nose";s:5:"long3";s:5:"mouth";s:4:"big3";s:3:"eye";s:6:"small3";}"
  "nose" => "long3"
  "mouth" => "big3"
  "eye" => "small3"]
Copy after login

第二个循环分析

$newExp = []; foreach ($exp as $v) {     if ($v['mouth'] == "big3"){         $newExp[] = $v;
     }
 }
 dump($newExp);
Copy after login

在这儿我们是做了一个常规的循环来循环exp而且在该循环中我们使用的是变量并没有使用引用。差别就是$v&$v请仔细看。
在这个循环中其实$v依旧是exp最后一个元素的引用。那么在循环中其实每次都是奖exp当前(current)的值赋值给$v因为引用关系最终改变的是exp最后一个元素的值。那么在foreach中exp最后子元素的值一直是变的。演变过程如下

//为了篇幅简略表示//第一次循环exp变为:也就是第一个元素赋值给了最后一个元素[
    [        'name' => 'test1',
        ...
    ],
    [        'name' => 'test2',
        ...
    ],
    [        'name' => 'test4',
        ...
    ],
    [        'name' => 'test1',
        ...
    ],
]//第二次循环exp变为:也就是第二个元素赋值给了最后一个元素[
    [        'name' => 'test1',
        ...
    ],
    [        'name' => 'test2',
        ...
    ],
    [        'name' => 'test4',
        ...
    ],
    [        'name' => 'test2',
        ...
    ],
]//第三次循环exp变为:也就是第三个元素赋值给了最后一个元素[
    [        'name' => 'test1',
        ...
    ],
    [        'name' => 'test2',
        ...
    ],
    [        'name' => 'test4',
        ...
    ],
    [        'name' => 'test4',
        ...
    ],
]//第四次循环exp变为:也就是第四个元素赋值给了最后一个元素 循环完毕[
    [        'name' => 'test1',
        ...
    ],
    [        'name' => 'test2',
        ...
    ],
    [        'name' => 'test4',
        ...
    ],
    [        'name' => 'test4',
        ...
    ],
]
Copy after login

原因分析

从上可以看出虽然本来exp的最后一个元素复合if条件中的 $v['mouth'] == "big3",但是在循环最后一个元素时其本身已经变成了第三个元素,所以mouth=big3的元素不存在了。这个流程有点儿绕,多看几遍就能看得懂。当然你也可以看看PHP的zend引擎中关于foreach的实现以及查看VLD中间代码,例如简单循环的VLD

number of ops:  16compiled vars:  !0 = $arr, !1 = $key, !2 = $rowline     # *  op                           fetch          ext  return  operands---------------------------------------------------------------------------------   2     0  >   INIT_ARRAY                                       ~0      1
         1      ADD_ARRAY_ELEMENT                                ~0      2
         2      ADD_ARRAY_ELEMENT                                ~0      3
         3      ADD_ARRAY_ELEMENT                                ~0      4
         4      ADD_ARRAY_ELEMENT                                ~0      5
         5      ASSIGN                                                   !0, ~0
   4     6    > FE_RESET                                         $2      !0, ->14
         7  > > FE_FETCH                                         $3      $2, ->14
         8  >   ZEND_OP_DATA                                     ~5
         9      ASSIGN                                                   !2, $3
        10      ASSIGN                                                   !1, ~5
   5    11      ECHO                                                     !1
        12      ECHO                                                     !2
   6    13    > JMP                                                      ->7
        14  >   SWITCH_FREE                                              $2
   7    15    > RETURN                                                   1
Copy after login

The above is the detailed content of Exception handling after using & referencing foreach in php. 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 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1251
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

See all articles