php for loop traverses index array

The word "traverse" literally means to read and access them all one after another and display them.

Because the for loop is a simple counting loop, and the subscript of the index array is an integer value. Therefore, we can iterate through the index array through a for loop.

We know that the index array subscript is an integer. We define the following array:

<?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 />';

}

?>

Through the above example, we loop the array.
Because the subscript starts from 0, define $i=0. Let $i increase by 1 each time it loops, but it must be less than 10, because the maximum value of the array subscript is 9.

In this way, we have learned to traverse the indexed consecutive subscript array.

Then the question is:

What to do with associative arrays? What if the subscripts of the index array are not consecutive?
Answer: We will talk about it in the next chapter, young man, don’t worry.


Continuing Learning
||
<?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 />'; } ?>
submitReset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!