Functions in PHP--the use of foreach () _php tips

Source: Internet
Author: User
PHP 4 introduces a foreach structure, which is similar to Perl and other languages. This is just a simple way to traverse an array. foreach can only be used in arrays, and an error occurs when you try to use them for other data types or for an uninitialized variable. There are two types of syntax, the second is a useful extension that is minor but is the first.
Copy Code code as follows:

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

the first form traverses the given array_expression array. In each loop, the value of the current cell is assigned to the $value and the pointer inside the array moves forward one step (so the next cell will be taken in the next loop).

The second format does the same thing, except that the key name of the current cell is assigned to the variable $key in each loop.
From PHP 5, you can also traverse objects.

Note:
When foreach starts executing, the pointer inside the array automatically points to the first cell. 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, not the array itself. The foreach array pointer has some side effects. Do not rely on the value of the array pointer, either in a Foreach loop or after a loop, unless you reset it.
Since PHP 5, you can easily modify the elements of an array by adding & before $value. This method assigns a value to a reference instead of copying a value.
Copy Code code as follows:

<?php
$arr = Array (1, 2, 3, 4);
foreach ($arr as & $value) {
$value = $value * 2;
}
$arr is now Array (2, 4, 6, 8)
?>

This method is available only if the traversed array can be referenced (for example, a variable).
Copy Code code as follows:

<?php
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.