PHP for loops and foreach loops

Source: Internet
Author: User

For loops in PHP

<? PHP $arr Array ("A", "B", "C");  for $i $i Count ($arr$i+ +)    {echo$arr[$i];}; // count equals the length?> in JS

optimization

<? PHP $arr Array ("A", "B", "C", ' d '); $num Count ($arr);  for $i $i $num $i+ +)    {echo$arr[$i]. ' <br> ';}; // count equals the length?> in JS

In PHP, the For loop is not commonly used, and the most commonly used is the Foreach Loop

foreach Loop

<? PHP     $arr Array ("A", "B", "C", ' d ', ' e ');     foreach ($arras$value) {        echo "{$value}<br>"  ;        };? >

The power of foreach is that it can output subscript

<? PHP     $arr Array ("A", "B", "C", ' d ', ' one ' = ' e ');     foreach ($arras$key$value) {        echo ' {$key}--- {$value}<br> ";        };? >

See an example of an array turning into a table

<?PHP$group= [        [' Name ' = ' Zs ', ' age ' = ', ' sex ' = ' male ', ' email ' = ' [email protected] ',        [' Name ' = ' as ', ' age ' = ', ' sex ' = ' female ', ' email ' = ' [email protected] ',        [' Name ' = ' Zs ', ' age ' = ', ' sex ' = ' male ', ' email ' = ' [email protected] ',        [' Name ' = ' as ', ' age ' = ', ' sex ' = ' female ', ' email ' = ' [email protected] ',        [' Name ' = ' Zs ', ' age ' = ', ' sex ' = ' male ', ' email ' = ' [email protected] ',        [' Name ' = ' as ', ' age ' = ', ' sex ' = ' female ', ' email ' = ' [email protected] ',        [' Name ' = ' Zs ', ' age ' = ', ' sex ' = ' male ', ' email ' = ' [email protected] ',        [' Name ' = ' as ', ' age ' = ', ' sex ' = ' female ', ' email ' = ' [email protected] ']    ]; Echo' <table border= ' 1 "width=" align= "Center" > "; Echo' <caption>; //foreach Loop    foreach($group  as $row){        Echo' <tr> '; foreach($row  as $col){            Echo' <td> '.$col.‘ </td> ';        }; Echo' </tr> '; };?>

php for loops and foreach loops

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.