+ 5
php
Hi I am trying to make a php script that take an array from an html form and remove all the numbers that are not primes. here is my code: https://code.sololearn.com/wA6a24A6a17a the problem is that when I run some times it give me wrong output. like when I enter 9 it does not remove that number from the array.
3 Respuestas
+ 3
Your sizeof($num) for loop has a bug. If you remove an element, that'll change what sizeof evaluates to and it'll prevent you from iterating over all the indexes of the array. Your array in PHP is more like a hash map. When you unset a key in it, keep in mind that it won't just shift all values after it to be associated with a decremented key.
This will work instead since it stores the sizeof value before entering the loop that changes the number of elements in the array:
if(isset($_POST['submit'])){
$num = explode(" ", $_POST['num']);
foreach ($num AS $index => $value)
$num[$index] = (int)$value;
$s = sizeof($num); // store so the loop won't end prematurely.
for($i = 0; $i < $s; $i++){
for($j = 2; $j < $num[$i]; $j++){
if (is_int($num[$i] / $j)){
unset($num[$i]);
break;
}
}
}
var_dump($num);
}
If I wasn't trying to minimize changes to your code, I'd use another foreach loop instead of using sizeof. Also, checking the result of modulus(%) is more often how people check divisibility instead of is_int.
+ 1
Josh Greig Thanks!
0
9