Let's talk about a pitfall referenced by foreach in PHP. let's take a look at the following code:
$ Val) {// some code} echo $ val; // output dog echo $ key; // output 3 // assign a value to the following val values: $ val = 'e '; print_r ($ arr); // output Array ([0] => apple [1] => banana [2] => cat [3] => dog)
Note: In the preceding foreach loop, $ key and $ val variables are not automatically released after the loop ends. The value is saved. Changing the value of $ val does not affect $ arr.
Reference: If you want to modify the elements of an array during array traversal, you can reference $ val in foreach. The referenced element $ val points to the memory address of the current array element, that is, the shared memory address. Therefore, changing the value of $ val changes the value of $ arr [$ key] at the same time.
Let's take a look at the following section using the referenced code in foreach. this is a situation recently encountered in the project:
& $ Val) {$ val = 'New Value';} echo $ val; // Output new value echo $ key; // output 3 $ val = 'egg '; print_r ($ arr); // output Array ([0] => new value [1] => new value [2] => new value [3] => egg)
Note: After foreach is used and referenced, $ key and $ val variables are not automatically released after foreach ends, but $ val and $ arrcount ($ arr) -1 points to the same memory address. Therefore, changing the value of $ val also changes the value of $ arr [3.
In this case, it is easy to make a mistake, as shown in the above example, to continue using variables referenced by foreach outside the loop, so that developers will not get the expected data. Therefore, to avoid this situation, release the reference of the variable at the appropriate position. The above code is used as an example:
& $ Val) {$ val = 'New Value';} unset ($ val); echo $ val; // error, Notice: Undefined variable: val echo $ key; // output 3 $ val = 'egg'; print_r ($ arr ); // output Array ([0] => new value [1] => new value [2] => new value [3] => new value) after foreach ends, unset $ val is released. Therefore, changing $ val will not affect $ arr.
This is a summary of the pitfalls and Solutions recently encountered in the project. if you have any errors or better suggestions, please note.