Home > Backend Development > PHP Tutorial > PHP leaves array reference problem after foreach loop

PHP leaves array reference problem after foreach loop

不言
Release: 2023-03-23 17:44:01
Original
2209 people have browsed it

The content of this article is about the reference problem of the array left by PHP after the foreach loop. Now I share it with you. Friends in need can take a look.

eg:



result:


Explanation:

1.foreach It is not a block-level field, the array reference ends, $k, $a does not release memory

2. When the first reference cycle ends, $a points to the last element of the array4

3 .When the loop starts for the second time (at this time $a already points to the last element and is a reference)

Loop 4 times. The changes in the array are:

1-> [1,2,3,4]

2-> [1,2,3,4]

3-> [1, 2,3,3] The third time value points to the last element 3 But value is a global reference pointing to the last element in the last cycle, so when value=3 it will also be The value of the last element is changed to 3

4-> [1,2,3,3]



# #Notes:

1. The implementation principle of foreach has the concept of internal pointers

2. When the foreach loop ends, the pointer will point to the last element


How to avoid:

After using &foreach loop unset ($a)

Related recommendations:

foreach reference passing address in PHP

Exception handling after using & reference in foreach in php

Analysis between foreach and normal for loop efficiency

The above is the detailed content of PHP leaves array reference problem after foreach loop. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template