1

I have to make a PHP script that calculates prime numbers. I never made something in PHP before.. (only in Ruby and JavaScript) I already tried to convert the script to PHP (see below) can someone explain me why it doesn't print down the first two prime numbers (2 & 3)? It worked in my ruby script.

<?php
$k = 0;
function primeNumber($n) {
 $flag = true;
 $i = 2;
 while($i <= ($n / 2) && $flag == true) {
   if ($n % $i == 0) {
     $flag = false;
     break;
   }else {
     $i++;
   }
   return $flag;
 }
}
while ($k <= 100) {
 if (primeNumber($k)) {
   echo $k."</br>";
 }
 $k++;
}

?>

Please dont remake the script completely, cause I understand it while doing it this way. :)

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Stijn Westerhof
  • 233
  • 3
  • 13
  • 1
    Maybe you want to move `return $flag;` to the end outside of the loop. – AbraCadaver Feb 17 '16 at 20:48
  • 1
    Why not use a conventional [`for` loop](http://php.net/manual/en/control-structures.for.php) instead of this quirky, manual `while` style? `for($k = 0; $k <= 100; $k++)` would be more concise. – tadman Feb 17 '16 at 20:50
  • Okay thanks for the feedback! I used both of your suggestions, and it worked :) – Stijn Westerhof Feb 17 '16 at 21:00

0 Answers0