Ways to use & in foreach in PHP

Source: Internet
Author: User

At first I didn't understand why I used the foreach when I was using the &

It was later found to be useful when adding data to an array

<?php
Header ("Content-type:text/html;charset=utf-8");
$pro _arr = Array (
Array (' Price ' =>10, ' count ' = 100),
Array (' Price ' =>20, ' count ' = + 90)
);

foreach ($pro _arr as $val) {
echo $val [' price ']. ' -'. $val [' count '];
Echo ' <br/> ';
}


Instead of using a new array to store the results, insert the old array directly into the new array.
foreach ($pro _arr as & $val) {
$val [' Total ']= $val the [' Price ']* $val [' count '];
}

foreach ($pro _arr as $val) {
echo $val [' price ']. ' -'. $val [' count ']. ' -'. $val [' Total '];
Echo ' <br/> ';
}
?>

This is very convenient to use, we hope to be useful to everyone

Ways to use & in foreach in PHP

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.