Home > Backend Development > PHP Tutorial > 玩转php数组(3)

玩转php数组(3)

WBOY
Release: 2016-06-13 12:51:41
Original
839 people have browsed it

玩转php数组(三)

<?php

//数组的for循环与foreach循环 
$arr=array('鑫','华','生','态','木','www.xinhuastm.com');


for($i=0;$i<count($arr);$i++){
   
   echo $arr[$i],'<br/>';
     
}

// 优化这道题,细节能体现一个人的水平 

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

     echo $arr[$i],'<br/>';
}
/*
结果:
鑫
华
生
态
木
www.xinhuastm.com
*/

// 这一次,for循环没有规律可循,再用for循环不灵了..... 
// 引入foreach 
//foreach是怎么工作的呢? 

$arr=array('name'=>'爱博生态木','url'=>'www.lyaibo.com','writer'=>'小王','time'=>'2013-3-16');

foreach($arr as $k=>$v){//这是说:循环数组的每个单元,把单元的键赋给$k,值赋给$v
   
   echo $k,'~',$v,'<br/>';
}
echo $k,'~',$v; // 停留在最后一次赋值的情况 
/*结果:
name~爱博生态木
url~www.lyaibo.com
writer~小王
time~2013-3-16
time~2013-3-16
*/
// 有人说,我不想循环时,要数组的键,我只是想循环着打印每个单元值 
echo '<hr />'; 

foreach($arr as $v){
   echo $v,'<br/>';
}
/*结果
爱博生态木
www.lyaibo.com
小王
2013-3-16
*/

// 有人说,我不想循环时,要数组的值,我只想循环打印数组的键 
foreach($arr as $k) { 
    echo $k,'<br />'; // 打印的还是值,$k只是被赋值而已 
} 
// 有人说这样 
/* 
foreach($arr as $k=>) { // 语法错误 
    echo $k,'<br />'; 
} 
*/ 
?>
Copy after login


 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template