php - 如何在php中一次点击打印一个数组

标签 php arrays primes

我需要一次“单击”一次打印一个数组(更具体地说是质数)。我已经创建了素数数组,但我不确定它如何运行,就像用户单击“下一个”按钮,下一个素数出现,然后他单击下一个,另一个素数出现。或者也许有更好的方法来做到这一点?

这是素数数组:

$primes = array();
for ($x = 2; $x <= 1000; $x++) {
    $xIsPrime = TRUE;
    $sqrtX = sqrt($x);
    foreach ($primes as $prime) if ($prime > $sqrtX || ((!($x % $prime)) && (!$xIsPrime = FALSE))) break;
    if ($xIsPrime) echo ($primes[] = $x)  . "<br>";
}

最佳答案

这些事情最好用 Javascript 来完成,但是,由于您的问题被标记为 PHP,所以我编写了以下代码:

<?php
$primes = array(2,   3,   5,   7,  11,  13,  17,  19,  23,  29, 
               31,  37,  41,  43,  47,  53,  59,  61,  67,  71, 
               73,  79,  83,  89,  97, 101, 103, 107, 109, 113, 
              127, 131, 137, 139, 149, 151, 157, 163, 167, 173);
// Add as many primes as you wish to the array
$num = array_key_exists("hid", $_POST) ? $_POST["hid"]+1 : 0;
?>
<html>
<head>
<!-- Put your meta tags, title, Javascript and CSS here -->
</head>
<body>
<form method="POST">
<h2><?php print($primes[$num]); ?></h2>
<?php
if(sizeof($primes)-$num > 1){
?>
<input type="hidden" name="hid" value="<?php print($num); ?>"/>
<input type="submit" name="sub" value="Next Prime"/>
<?php
}
else{
?>
<input type="submit" name="sub" value="Next Prime" disabled/>
<?php
}
?>
</form>
</body>
</html>

关于php - 如何在php中一次点击打印一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20945325/

相关文章:

php - 如何在codeigniter中回显用户上传的文件?

javascript - 我尝试过滤空值。但是,TypeError : Cannot read property 'length' of null

c - 查找素数执行的程序需要一些时间

php - 如何检查尚未自动加载的类是否存在

php - Mysql 错误处理

php - 如何使用 Eloquent Query Builder 对与同一张表的关系使用 whereHas?

c - 如何使用 C 选择数组中的多个元素?

javascript - jQuery 中的数组函数

haskell - 使用 haskell 项目 Euler prob 10

python - 是否存在用于 Python 的素数相关函数库?