将整数放置到for循环内的数组的下一个可用位置

时间:2015-02-16 13:23:48

标签: php

您好我试图找出如何迭代整数,确定它们是否为素数,然后将素数放在一个数组中,将非素数放在另一个数组中。

我已经完成了检查质数的功能,为简单起见我将省略。我似乎无法将值放入不同的数组中。这是我到目前为止所拥有的。

对此有任何见解表示赞赏,我已经搜索了很多以前的问题,但似乎无法提出一个有效的答案,即使这看起来很直接。

    <?php

              $start = 0;
              $end = 1000;
              $primes = array();
              $nonPrimes = array();


              for($i = $start; $i <= $end; $i++)
              {
                  if(isPrime($i))
                  {
                    //add to the next available position in $primes array;
                  }
                  else
                  {
                  //add to the next available position in $nonPrimes array;
                  }
              }
?>

2 个答案:

答案 0 :(得分:1)

array_push也许?

if(isPrime($i))
{
    //add to the next available position in $primes array;
    array_push($primes,$i);
}
else
{
    //add to the next available position in $nonPrimes array;
    array_push($nonPrimes,$i);
}

答案 1 :(得分:1)

使用[]运算符向数组添加元素:

if (isPrime($i)) 
{
    $primes[] = $i;
}
else
{
    $nonPrimes[] = $i;
}

这将产生如下数组:

$primes[2, 3, 5, 7, 11];

$nonPrimes[1, 4, 6, 8, 9, 10];