<?php

function is_prime($prime) {  
    if($prime < 1)
        return false;

	if($prime == 1) 
		return true;
	if($prime == 2)
		return true;
    $sqrt = sqrt($prime);
    for ($i = 3; $i <= $sqrt; $i+=2){
        if ($prime%$i == 0) return false; 
    } 
    return true; 
}

if (($handle = fopen("primes1000000.txt", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if ($data[1] >= 1000000)
            break;
        //If there's an even digit (or a 5) we can instantly exclude it as when rotated it will not not be a prime.
        if (
            strpos((string) $data[1], "0") !== false ||
            strpos((string) $data[1], "2") !== false ||
            strpos((string) $data[1], "4") !== false ||
            strpos((string) $data[1], "5") !== false ||
            strpos((string) $data[1], "6") !== false ||
            strpos((string) $data[1], "8") !== false
        ) {

            continue;
        }
        $primes[] = (int) $data[1];
    }
    fclose($handle);
}
echo "File read\n";

$count = 1+1; //2 and 5 are primes but not included
foreach($primes as $prime) 
{
        //echo "Now testing $prime\n";
        $newprime = $prime;
        for($rotate = 1; $rotate < strlen($prime); $rotate++)
        {
            $newprime = substr($newprime, -1, 1).substr($newprime, 0, -1);
            //echo "New prime: $newprime\n";
            if(!in_array($newprime, $primes))
            {
                continue 2;
            }

        }
        $count++;
        echo $prime.PHP_EOL;


}

echo "Total: $count\n";