duanla3319 2013-09-22 10:57
浏览 26
已采纳

简单的PHP for循环错误

Just started learning. Here's what I have:

<?php 
$i = 0;
$num = $i * 12;

for ($i=0; $i<13; $i++) {

echo($i." times 12 = ".$num."<br>");
}

?>

The outcome should be:

1 times 12 = 12

2 times 12 = 24

3 times 12 = 36

etc...

The outcome I actually get is:

1 times 12 = 0

2 times 12 = 0

3 times 12 = 0

any ideas?

  • 写回答

7条回答 默认 最新

  • dongting7352 2013-09-22 10:59
    关注

    It is because you have this declaration before for loop:

    $i = 0; $num = $i * 12;
    

    so always $num will be 0. Just place it into for:

    for ($i=1; $i<13; $i++) {
       $num = $i*12;
       echo($i." times 12 = ".$num."<br>");
    }
    

    You don't need declare $i variable before for loop. This variable will be overwritten. There is simple test:

    $i = 5;
    for($i = 1; $i<10; $i++);
    
    echo $i;
    

    OUTPUT:

    10
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题