Usage of functions in PHP-foreach ()

Source: Internet
Author: User
This article provides a detailed analysis of the usage of the foreach () function in PHP. For more information, see The foreach structure introduced in PHP 4, which is similar to Perl and other languages. This is just a simple way to traverse arrays. Foreach can only be used for arrays. an error occurs when you try to use it for another data type or an uninitialized variable. There are two types of syntax. The second type is secondary, but it is the first type of useful extension.

The code is as follows:


Foreach (array_expression as $ value)
Statement
Foreach (array_expression as $ key => $ value)
Statement


The first format traverses the given array_expression array.In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ).

In the second format, only the key names of the current unit are assigned to the variable $ key in each loop.
Objects may be traversed from PHP 5.

Note:
When foreach starts to execute, the pointer inside the array automatically points to the first unit. This means that you do not need to call reset () before the foreach loop ().

Note:
Unless the array is referenced, foreach operates on a copy of the specified array, rather than the array itself. Foreach has some side effects on array pointers. Do not depend on the value of the array pointer in a foreach loop or after a loop unless it is reset.
Since PHP 5, you can easily add & before $ value to modify the elements of the array. This method will assign values by reference instead of copying a value.

The code is as follows:


$ Arr = array (1, 2, 3, 4 );
Foreach ($ arr as & $ value ){
$ Value = $ value * 2;
}
// $ Arr is now array (2, 4, 6, 8)
?>


This method is only available when the retrieved array can be referenced (for example, a variable ).

The code is as follows:


Foreach (array (1, 2, 3, 4) as & $ value ){
$ Value = $ value * 2;
}
?>

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.