search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

首页课程PHP Fun Breakthrough Classfor loop iterates through index array

for loop iterates through index array

目录列表

for循环遍历索引数组

遍历二字,从字面解释就是一个接一个全读访问一次,显示出来。

因为for循环是一个单纯的计数型循环,而索引数组的下标为整型的数值。因此,我们可以通过for循环来遍历索引数组。

我们知道索引数组下标为整型。我们定义下面的一个数组:

<?php

//声明一个数组,值为1到10
$num = array(1,2,3,4,5,6,7,8,9,10);
//按照索引数组的特点,下标从0开始。所以1的下标为0,10的下标为9
echo $num[0].'<br />';
echo $num[9].'<br />';

//我们可以得到数组中元素的总个数,为10
echo count($num);

//遍历这个索引数组的话,我们就可以定义一个变量为$i
//$i 的值为0,从0开始
//可以设定一个循环条件为:$i 在下标的(9)最大值之内循环
for($i = 0 ; $i < count($num) ; $i++){
   echo $num[$i].'<br />';
}

?>

通过上面的例子,我们就把数组进行了循环。

因为下标是从0开始的,定义$i=0 。每次循环的时候让$i 加1 ,但是必须要小于10,因为数组下标的最大值为9。

这样,我们就学会了了对索引连续下标数组的遍历。

填空,遍历出$boy数组里的男孩名字。

<?php $boy = array('小明','小光','小强'); ($i = ; $i < ($boy) ; $i++){ echo $boy[$i].'<br />'; } ?>

1/2