Php 使用循环使用前100个素数填充数组

Php 使用循环使用前100个素数填充数组,php,Php,我一直在使用php函数创建素数数组。到目前为止,我已经把它工作到列出了从2到1000的所有素数的位置。我现在要做的是使用递增计数

我一直在使用php函数创建素数数组。到目前为止,我已经把它工作到列出了从2到1000的所有素数的位置。我现在要做的是使用递增计数<100或类似的方法生成前100个素数。这是我目前的代码

<?php

function prima($n)
{
$primeNumbers = []; // Initiate result array
for ($i = 1; $i <= $n; $i++)
    {
    $counter = 0;
    for ($j = 1; $j <= $i; $j++)
        {
        if ($i % $j == 0)
            {
            $counter++;
            }
        }

    if ($counter == 2)
        {
        $primeNumbers[] = $i; // store value to array
        }
    }

return json_encode($primeNumbers); // return converted json object
}

header('Content-Type: application/json'); // tell browser what to expect
echo prima(1000); // echo the json string returned from function

?>


在for循环的末尾,添加'if(count($primeNumbers)==100)break;'

当您达到极限时,只需中断循环:
if($counter==100)中断这就是我想做的。非常感谢。