码迷,mamicode.com
首页 > Web开发 > 详细

PHP的for循环和foreach循环

时间:2016-05-03 12:24:06      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

 

PHP中的for循环

<?php

$arr = array("a", "b", "c");

for( $i = 0; $i < count($arr); $i++){
    echo $arr[$i];
};

// count 相当于js中的 length

?>

 

优化一下

<?php

$arr = array("a", "b", "c", ‘d‘);

$num = count($arr);

for( $i = 0; $i < $num; $i++){
    echo $arr[$i].‘<br>‘;
};

// count 相当于js中的 length

?>

 

在php中, for循环其实并不常用, 最常用的还是foreach循环

 

foreach循环

<?php

    $arr = array("a", "b", "c", ‘d‘, ‘e‘);

    foreach($arr as $value){
        echo "{$value}<br>";    
    };

?>

 

foreach的强大之处在于可以输出下标

<?php

    $arr = array("a", "b", "c", ‘d‘, ‘one‘=>‘e‘);

    foreach($arr as $key => $value){
        echo "{$key}---{$value}<br>";    
    };

?>

 

看一个数组转成表格的实例

<?php

    $group = [

        [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘],
        [‘name‘ => ‘as‘ , ‘age‘ => 17 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘],
        [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘],
        [‘name‘ => ‘as‘ , ‘age‘ => 20 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘],
        [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘],
        [‘name‘ => ‘as‘ , ‘age‘ => 20 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘],
        [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘],
        [‘name‘ => ‘as‘ , ‘age‘ => 20 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘]

    ];

    echo ‘<table border="1" width="800" align="center">‘;

    echo ‘<caption><h1>数组转表格实例</h1></caption>‘;


    // foreach循环

    foreach($group as $row){

        echo ‘<tr>‘;

        foreach($row as $col){
            echo ‘<td>‘.$col.‘</td>‘;
        };

        echo ‘</tr>‘;
    };

?>

 

PHP的for循环和foreach循环

标签:

原文地址:http://www.cnblogs.com/carol1987/p/5454309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!