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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备