PHPforeach-php Tutorial

Source: Internet
Author: User
Tags php foreach
PHPforeach reference & lt ;? Php $ aarray (str1 & gt; val1, str2 & gt; val2, str3 & gt; val3, str4 & gt; val4,); $ barray (str1, str2, str3, str4,); foreach ($ ba PHP foreach reference
   'val1','str2' => 'val2','str3' => 'val3','str4' => 'val4',);$b = array('str1', 'str2','str3','str4',);foreach ($b as &$val) {$val = $a[$val];}unset($val);foreach ($b as $val) {echo "-----$b[3]";echo $val."\n";}?>

'Val1', 'str2' => 'val2', 'str3' => 'val3', 'str4' => 'val4 ',); $ B = array ('str1', 'str2', 'str3', 'str4',); foreach ($ B as & $ val) {$ val = $ a [$ val];} foreach ($ B as $ val) {echo "----- $ B [3]"; echo $ val. "\ n" ;}?>

Output:

----- Val1val1
----- Val2val2
----- Val3val3
----- Val3val3


As you can see, because the last $ [2] reference of the first foreach reference is not closed, the address is constantly being written in the second foreach;

Print the value of $ B [2. With foreach running, the value of $ B [2] is constantly changing. This causes the value of $ B [2] When foreach runs to $ B [1 ].

It is equal to $ B [1]. in the last run, $ B [2] = $ B [2] is the same as $ B [1 ].

Solution:

Use the unset () method to release the referenced variable before the second foreach loop.

   'val1','str2' => 'val2','str3' => 'val3','str4' => 'val4',);$b = array('str1', 'str2','str3','str4',);foreach ($b as &$val) {$val = $a[$val];}unset($val);foreach ($b as $val) {echo "-----$b[3]";echo $val."\n";}?>


Output result:

----- Val4val1
----- Val4val2
----- Val4val3
----- Val4val4

Solution 2 (not good ):

   'val1','str2' => 'val2','str3' => 'val3','str4' => 'val4',);$b = array('str1', 'str2','str3','str4',);foreach ($b as &$val) {$val = $a[$val];}// unset($val);foreach ($b as $item) {echo "-----$b[3]";echo $item."\n";}?>

Replace the as variable in the second foreach without using the referenced variable.

Output:

----- Val4val1
----- Val4val2
----- Val4val3
----- Val4val4

Conclusion: We recommend that you use unset () to release it after Reference.

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.