+ 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.

11th Apr 2021, 5:49 PM
tibi
tibi - avatar
3 Answers
+ 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.
12th Apr 2021, 1:24 AM
Josh Greig
Josh Greig - avatar
+ 1
Josh Greig Thanks!
12th Apr 2021, 7:19 AM
tibi
tibi - avatar
0
9
19th Dec 2023, 5:34 PM
Musharraf