Home > Article > Backend Development > Let’s go deeper into the foreach loop and unset() function. Let the master explain it to me.
<code> foreach($arr as $key=>$val){ if(in_array($val,$pattern)){ unset($arr[$key]); break; } } foreach($arr as $key=>$val){ if(in_array($val,$pattern)){ unset($val); break; } } 贴了部分代码,我就想问一下unset()函数时,为什么是unset($arr[$key]);而不是unset($val);不知道懂不懂我的意思</code>
<code> foreach($arr as $key=>$val){ if(in_array($val,$pattern)){ unset($arr[$key]); break; } } foreach($arr as $key=>$val){ if(in_array($val,$pattern)){ unset($val); break; } } 贴了部分代码,我就想问一下unset()函数时,为什么是unset($arr[$key]);而不是unset($val);不知道懂不懂我的意思</code>
Let me briefly explain the difference:
unset($arr[$key]) //What is destroyed is an element in the $arr array
unset($val) //When destroyed, the variable $val is an element in $arr, which is equivalent to reopening a variable. Destroying the reopened variable will not affect the original array $arr. .
I wonder if you have any questions?
<code>foreach($arr as $key=>$value) { $key和$value //这里是重新初始化的一个全新的变量,和 $arr 无关 }</code>