1.通过for循环将数组中值求和、求平均值
<?php $num=[1,2,3,4,5,6,7,8,9]; $sum = 0; for ($i=0,$n=count($num); $i < $n ; $i++) { $sum += $num[$i]; } echo '和是: ' .$sum,'<br>'; echo '平均值: '.number_format($sum/count($num),1); ?>
______________________________________________________________________________
2.数组翻转
<?php $stu=['wang','li','zhang','sun','jiang','liu','xu']; for ($i=0, $j=count($stu)-1; $i < $j; $i++, $j--) { [$stu[$i],$stu[$j]] = [$stu[$j],$stu[$i]]; } print_r($stu); ?>
______________________________________________________________________________
3.遍历二维数组
<?php $stu=[ [1,2,3,4], ['a', 'b', 'c', 'd'] ]; for ($i=0; $i < count($stu); $i++) { for ($j=0; $j < count($stu[$i]); $j++) { echo $stu[$i][$j],' '; } } ?>
______________________________________________________________________________
4.
<?php for ($i=100; $i <= 999; $i++) { $a = (int)($i/100); $b = (int)(($i%100)/10); $c = $i % 10; if ($i == pow($a,3) + pow($b,3) + pow($c,3)) { echo $i,'<br>'; } } ?>
______________________________________________________________________________
5.打印100以内的斐波那契数(迭代法)
<?php $num1 = 1; $num2 = 1; echo $num1,' ',$num2,' '; while (true) { $num3 = $num1 + $num2; if ($num3 > 100) { break; } echo $num3,' '; $num1 = $num2; $num2 = $num3; } ?>