Explanation of "foreach" loop statement examples in PHP loop control statements

Source: Internet
Author: User
In PHP, the foreach loop statement is used to traverse arrays cyclically. This chapter introduces a special loop statement in PHP, "foreach" loop statement.

What is foreach loop used?

Bytes

Foreach loop syntax format

The foreach loop syntax can be written in either of the following ways:

foreach (array_variable as val)     statement;

Array_variable represents an array variable. during each loop execution, the values of each element are temporarily assigned to the variable val. the values of the val obtained by each statement are different.

Method 2

foreach (array_variable as key => val)     statement;

Key indicates the subscript of the array, and val indicates the value of the array. for the number subscript array, the key value in each loop is a number that grows from 0.


Foreach loop instance

 ";}?>

Code running result:

The above example is the first way to use the foreach loop. in this case, if you want to get the $ key of the array, you need to use our second method. the code is as follows:

 1, "two" => 2, "three" => 3, "seventeen" => 17); foreach ($ a as $ key => $ val) {echo $ key. ":". $ val."
";}?>

Code running result:

The two examples above are simple application of the foreach loop statements.

The above is a detailed description of the "foreach" loop statement instance in PHP loop control statements. For more information, see other related articles in the first PHP community!

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.