dongtun3259 2018-07-04 16:28
浏览 59
已采纳

将for循环的输出推入数组


I am trying to push the output of a for loop into an array but I am not being able to do so. Following is the code that I have written:

<?php
$n = 14;
for ($i = 2; $i <= $n; $i++) 
{ 
    for ($j = 2; $j <= $n; $j++) 
    { 
        if ($i%$j == 0) // if remainder of $i divided by $j is equal to zero, break. 
        {
            break;
        }
    }
    if ($i == $j) // 
    {
        $form = $i;
        //echo $form;
        $numArray = array();
        array_push($numArray, $form); // Here I am trying to push the contents from the `$form` variable into the `$numArray`
        print_r($numArray);                 
    }
}
?>

The output that I obtain through this is:

Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 5 ) Array ( [0] => 7 ) Array ( [0] => 11 ) Array ( [0] => 13 )

Here, we see that the array index basically remains the same, so it has no scope for future use. So, how can I make this seem like as shown below:

Array ( [0] => 2 ) Array ( [1] => 3 ) Array ( [2] => 5 ) Array ( [3] => 7 ) Array ( [4] => 11 ) Array ( [5] => 13 )

Please note that, $n in the code can be any number less than 101 and greater than 1. Thank you for your precious time put into reading and trying to helping me out. :)

  • 写回答

1条回答 默认 最新

  • dongzongpeng6474 2018-07-04 16:32
    关注

    The $numArray should be declared once, not every time in the loop. And you can simply add value to the array by using expression like: $numArray[] = $i; Try this code:

    <?php
    
    $numArray = array();
    $n = 14;
    for ($i = 2; $i <= $n; $i++) {
        for ($j = 2; $j <= $n; $j++) {
            if ($i % $j == 0) { // if remainder of $i divided by $j is equal to zero, break. 
                break;
            }
        }
        if ($i == $j) {
            $numArray[] = $i;
        }
    }
    print_r($numArray);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集