dqqn32019 2015-08-05 06:20
浏览 52
已采纳

从for循环输出成对

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.

  • 写回答

1条回答 默认 最新

  • doufangpian5545 2015-08-05 06:22
    关注

    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>';
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用