# Prime Numbers in PHP

Prime numbers are having only two factors, one is 1 and other one is the number itself.
These are the first 5 prime numbers 2, 3, 5, 7, 11
Prime numbers are divisible by exactly two natural numbers, 1 and the number itself.
Checking and listing all prime numbers in PHP by using loop and form to take user inputs

## Checking numbers

Any number we can check if it is Prime number or not .
``````\$n1=18;
\$flag=0;
for(\$i=2;\$i<=(\$n1/2); \$i++){
if(\$n1%\$i == 0 ){
\$flag=1;
break;
}
}

if(\$flag==0){
echo  "\$n1 is a prime number " ;
}else{
echo  "\$n1 is NOT a prime number " ;
}	``````
Output
``18 is NOT a prime number``

## Sticky form to take user input

We will ask user to enter any number in a sticky form and then display the number is prime number or not.
is a prime number
``````\$n1=\$_POST['n1']; // change this number
echo "<form method=POST action=''>
<input type=text name=n1 value='\$n1'>
<input type=Submit value=submit></form>";
\$flag=0;
for(\$i=2;\$i<=(\$n1/2); \$i++){
if(\$n1%\$i == 0 ){
\$flag=1;
break;
}
}

if(\$flag==0){
echo  "\$n1 is a prime number " ;
}else{
echo  "\$n1 is NOT a prime number " ;
}	``````

## Listing all prime numbers

We will loop through a range of numbers and check and list of all the prime numbers. ( All prime numbers less than 100 )
``````for(\$j=1;\$j<=100;\$j++){
\$n1=\$j;
\$flag=0;
for(\$i=2;\$i<=(\$n1/2); \$i++){
if(\$n1%\$i == 0 ){
\$flag=1;
break;
}
}

if(\$flag==0){
echo  "\$n1 , " ;
}
}``````
Output is here
``````1 , 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43
, 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ,`````` Subscribe to our YouTube Channel here

## Subscribe

* indicates required
Subscribe to plus2net plus2net.com

Post your comments , suggestion , error , requirements etc here