Home > Backend Development > PHP Tutorial > Let's go deeper into the foreach loop and unset() function. Let the master explain it to me.

Let's go deeper into the foreach loop and unset() function. Let the master explain it to me.

WBOY
Release: 2016-08-10 09:07:31
Original
1218 people have browsed it

<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>
Copy after login
Copy after login

Reply content:

<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>
Copy after login
Copy after login

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>
Copy after login
Related labels:
php
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