当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Output as pairs from a for loop

问题描述:

I've got an array. Below is an example

$arr = ["apple", "mango", "chair", "table", "pink", "red"];

I need to access 2 at a time within a for loop.

for ($i=0;$i<$arr.length;$i++){

$var = 'First item is '.$arr[$i].' and the second is '.$arr[$i+1];

}

The 1st output is First item is apple and the second is mango.

But from the 2nd output is First item is mango and the second is chair.

I want to output in pairs. So the expected outputs are:

First item is apple and the second is mango

First item is chair and the second is table

First item is pink and the second is red

how do I do this? And I want to add a <br> tag at the end of each line except for the last.

网友答案:

3rd parameter of for loop is increment counter (counter modifier) so you can change that to make your loop work the way you want. you can put any expression there which will evaluate for the next run

for ($i=0;$i<$len;$i=$i+2){
   $var = 'First item is '.$arr[$i].' and the second is '.$arr[$i+1];
   $var .= ($i == $len-1) ? '' : '<BR>';
 }
分享给朋友:
您可能感兴趣的文章:
随机阅读: