A detailed explanation of the foreach usage in PHP

Source: Internet
Author: User

What is 1.foreach?

foreach is a grammatical structure of PHP, is actually a tool, (tool: Is the work of the use of the appliance), then in the program development process, in order to achieve the program effect, the use of foreach.

2. How to use?

Official:

foreach (array_expression as $value)    statement foreach (array_expression as $key = $value)  statement  
Example 1:
  
    $arr = Array (1,2,3,4);//define Array    foreach ($arr as & $value) {    $value = $value *2;//loop through and modify the values in the array    }    echo "<pre>";    Print_r ($arr);//Print out the final result

Result: (& $value is reference assignment)

Array (    [0] = 2  [1] = 4   [2] = 6   [3] = 8)  
Example 2:
  
            $a = Array (    "one" = 1, "One" =    2,    "three" = 3,    "Seventeen"); foreach ($a as $k =&G T $v) {echo "<pre>";    echo "[$k] = $v \ n";}    

Results:

    

[One] = 1
[2] + =
[Three] = 3
[Seventeen] = 17
Explanation: K actually refers to is key,v actually refers to is the value
Summary: foreach is used frequently in PHP projects, especially when working with arrays!
May 10, 2017 18:36:25 in Beijing

A detailed explanation of the foreach usage 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.