find the nth prime number in php

To find the nth prime number in PHP, you can use a function that generates prime numbers until you have found the nth one.

Here's a function that does just that:

main.php
function nthPrime($n) {
    $count = 0;
    $i = 2;

    while ($count < $n) {   // loop until we find the nth prime number
        $isPrime = true;
        for ($j = 2; $j < $i; $j++) {
            if ($i % $j == 0) {   // if we find a number that divides i without remainder, i is not a prime number
                $isPrime = false;
                break;
            }
        }
        if ($isPrime) {
            $count++;
        }
        $i++;
    }
    return $i - 1;   // subtract 1 from i to get the nth prime number
}
531 chars
20 lines

Example usage:

main.php
echo nthPrime(10);   // outputs 29
35 chars
2 lines

This will output 29, which is the 10th prime number.

gistlibby LogSnag