创建数组,分别用for/while/foreach()遍历

原创2019-08-15 16:38:5012
摘要:<?php          //for循环是计数型循环         function sum($mix,$max){         &n

<?php


         //for循环是计数型循环

         function sum($mix,$max){

                             $res=range($mix,$max);

                             echo '<pre>',var_export($res,true),'<br>';

                             $count=count($res);

                             echo $count,'<br>';

                             $total=0;

                             $i=0;

                             for($i=0;$i<$count;$i++){

                             $total+=$res[$i];

                 }

         echo $total;

         }

         sum(5,10);


         //while()入口判断型循环,用于一维数组循环

         function sum($mix,$max){

                         $res=range($mix,$max);

                         echo '<pre>',var_export($res,true),'<br>';

                         $count=count($res);

                         echo $count,'<br>';

                         $total=0;

                         $i=0;

                         while(isset($res[$i])){

                                     $total+=$res[$i];

                                     $i++;

                                 }

                         echo $total;

                 }

            sum(0,10);


             //foreach()入口判断型循环,多用于二维数组循环

             $res=[

                                 ['id'=>1,'name'=>'admin','qq'=>'13897290016'],

                                 ['id'=>2,'name'=>'root', 'qq'=>'13897290017'],

                                 ['id'=>3,'name'=>'user', 'qq'=>'13897290018'],

                                 ['id'=>4,'name'=>'super','qq'=>'13897290019']

                     ];

            //声名一个空数组,获取键名值

             $skey=[];

             //用内部指针输出键名及键名对应的值,就不必指定$var['键名'];

             foreach($res as $key=>$var){

                             // echo count($var);

                             echo key($var).':'.current($var).'-----';

                             next($var);

                             echo key($var).':'.current($var).'-----';

                             next($var);

                             echo key($var).':'.current($var),'<br>';

                             //把键名返回到$skey数组中

                             $skey=array_keys($var);

                     }

             echo var_export($skey,true);


批改老师:Peter-Zhu批改时间:2019-08-16 09:50:32
老师总结:实际开发中, 基本上都是可以用foreah来完成的

发布手记

热门词条

第九期线上培训班