Issues caused by using references in foreach

Source: Internet
Author: User
Don't say much nonsense, just look at the following code:

$arrarray('a','b','c','d');     foreach($arras &$v){}     foreach($arras$v){          var_dump($v);     }

After running, the results are as follows:

string'a' (length=1)string'b' (length=1)string'c' (length=1)string'c' (length=1)     //这里为什么是c呢?

We wonder why the last one is C and not d?

In fact, the reason is very simple, at the end of the first cycle, the variable v becomes a reference to arr[3]. So, when using foreach for the second time, it is the way to pass the value, which is actually to iterate over the value of the variable arr, then assign the value to the variable V, since the variable v is a reference to arr[3], so assigning the value to the variable v is actually assigned to ARR[3].

Let's Change the code:

$arrarray('a','b','c','d');     foreach($arras &$v){}     foreach($arras$v){          var_dump($arr);//这里把变量$arr打印出来     }

After running, you will find:

Array (size=4)0=string' A '(length=1)1=string' B '(length=1)2=string' C '(length=1)3= &string' A '(length=1) Array (size=4)0=string' A '(length=1)1=string' B '(length=1)2=string' C '(length=1)3= &string' B '(length=1) Array (size=4)0=string' A '(length=1)1=string' B '(length=1)2=string' C '(length=1)3= &string' C '(length=1) Array (size=4)0=string' A '(length=1)1=string' B '(length=1)2=string' C '(length=1)3= &string' C '(length=1)

It can be found that the value of arr[3] has been changing.

'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
  • '). Text (i)); }; $numbering. FadeIn (1700); }); });

    Copyright NOTICE: This article is the original blogger articles, reproduced please indicate the source.

    The above describes the use of references in foreach problems, including aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.