Example of a "foreach" loop statement in a PHP loop control statement

Source: Internet
Author: User
This section describes a special looping statement in PHP, the "foreach" loop statement.

What is a foreach loop for?

In PHP, the Foreach Loop statement, which is designed to iterate through an array, can be viewed in this article http://www.php.cn/php-weizijiaocheng-360217.html

foreach Loop syntax format

The Foreach Loop syntax is written in two ways, and the first one is as follows

foreach (Array_variable as Val)     statement;

Array_variable represents an array variable, and every time the loop executes, the value of each element is temporarily assigned to the variable val,statement the value of Val is different each time it gets

The second type of notation

foreach (array_variable as key = val)     statement;

The key represents the subscript of the array, and Val represents the value of the array, so for a numeric subscript array, the value of key in each loop is the number that grows from 0 onwards.


foreach Loop instance

<?phpheader ("Content-type:text/html;charset=utf-8");    Set the encoding $a=array ("Apple", "orange", "banana"), foreach ($a as $value) {    echo $value. <br/> ";}? >

Code Run Result:

Detailed Examples:

We said at the beginning that the "foreach" loop is dedicated to looping the array, so we first define an array of $ A, in which there are three values, namely "Apple", "orange", "banana", and then iterate through the array using the Foreach Loop statement, and the values in the output array.


The above example is the first way to use the Foreach Loop, at which point, if you want to get the $key of the array, use our second notation, the code is as follows:

<?phpheader ("Content-type:text/html;charset=utf-8");    Set the encoding $ A = Array ("one" + = 1, "one" + =    2,    "three" = 3,    "Seventeen" = +); foreach ($a as $key = = $val) {    echo $key. ":". $val. " <br/> ";}? >

Code Run Result:

The above two examples are the simple application of the Foreach Loop two kinds of notation.

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.