[英]Push the output of a for loop into an array
I am trying to push the output of a for loop into an array but I am not being able to do so. 我正在尝试将for循环的输出推入数组,但无法执行。 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 )
数组([0] => 2)数组([0] => 3)数组([0] => 5)数组([0] => 7)数组([0] => 11)数组([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 )
数组([0] => 2)数组([1] => 3)数组([2] => 5)数组([3] => 7)数组([4] => 11)数组([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. 请注意,代码中的
$n
可以是小于101且大于1的任何数字。感谢您宝贵的时间来阅读和尝试帮助我。 :) :)
The $numArray
should be declared once, not every time in the loop. $numArray
应该声明一次,而不是每次循环都声明。 And you can simply add value to the array by using expression like: $numArray[] = $i;
而且,您可以使用以下表达式简单地向数组添加值:
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.