数组的三种循环遍历效果图:
数组的三种循环遍历源代码:
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>数组的遍历技巧</title> <style type="text/css"> .box { width: 900px; margin: auto; } h3,h4 { text-align: center; } .box1 { float: left; } .box2 { float: right; } .box3 { float: left; padding-left: 250px; } .box4 { clear: both; } table { margin: auto; } th { color: red; } td { color:fuchsia; font-size: 1.2em; } </style> </head> <body> <?php $fruit = ['peach'=>'桃子', 'pear'=>'梨子', 'banana'=>'香蕉', 'plum'=>'李子', 'orange'=>'橙子', 'apple'=>'苹果']; echo '<div class=box>'; echo "<h3>数组的三种循环遍历for while foreach</h3>"; echo '<div class=box1>'; echo '<hr color="red">'; echo '<h4 style="color:red">for 循环遍历</h4>'; for ($i=0; $i<count($fruit);$i++) { echo key($fruit),':',current($fruit),'<br>';//查看数组的键和值 next($fruit);//指针指向下一个元素,并返回当前元素的值 } echo '</div>'; reset($fruit); //重置数组指针 echo '<div class=box2>'; echo '<hr color="blue">'; echo '<h4 style="color:blue">while 循环遍历</h4>'; $i = 0; while ($i<count($fruit)) { echo key($fruit),'=',current($fruit),'<br>';//查看数组的键和值 next($fruit); $i++; } echo '</div>'; echo '<div class=box3>'; reset($fruit); //重置数组指针 echo '<hr color="fuchsia">'; echo '<h4 style="color:fuchsia">foreach 循环遍历1</h4>'; echo '<ul>'; foreach ($fruit as $key => $value) { echo '<li>'.$key.'=>'.$value.'</li>'.'<br>';//查看数组的键和值 next($fruit); } echo '</ul>'; echo '</div>'; echo '<div class=box4>'; reset($fruit); //重置数组指针 echo '<hr>'; echo '<h4 style="color:fuchsia">foreach 循环遍历2</h4>'; echo '<table border="1" cellpadding="5" cellspacing="0">'; echo '<caption><h4>水果英文对照表</h4></caption>'; echo '<tr bgcolor="lightskyblue">'; foreach ($fruit as $key => $value) { echo '<th align="center">'.$key.'</th>'; } echo '</tr>'; echo '<tr>'; foreach ($fruit as $key => $value) { echo '<td align="center">'.$value.'</td>'; } echo '</tr>'; echo '</table>'; echo '<hr>'; echo '<h4 style="color:red">array_splice 增删改查操作</h4>'; //查看数组 echo '<h4 style="color:fuchsia">查看</h4>'; print_r($fruit); //查看数组 reset($fruit); //重置数组指针 echo "<pre>"; echo '<div class=box1>'; //删除 echo '<h4 style="color:fuchsia">删除</h4>'; array_splice($fruit,-3,2); print_r($fruit); echo '</div>'; echo '<div class=box2>'; //替换 echo '<h4 style="color:fuchsia">替换</h4>'; array_splice($fruit,-1,1,'柚子'); print_r($fruit);//把苹果换成柚子 echo '</div>'; echo '<div class=box3>'; //增加 echo '<h4 style="color:fuchsia">增加</h4>'; array_splice($fruit,count($fruit),1,'番石榴');//单独加一个元素 array_splice($fruit,count($fruit),1,['芒果','榴莲']);//添加一组元素 print_r($fruit); echo '</div>'; echo '</div>'; echo '</div>'; ?> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
array_splice 增删改查操作效果图:
array_splice 增删改查操作手抄图: