Home >>PHP Tutorial >PHP if Statement

PHP if Statement

if statement in PHP

The if Statement is the simplest conditional statements.

In if  Statements Output will appear when only Condition must be true.

If Statement works  much like the English language statement, "if X happens, then do Y."

Write a program to check even number.(Number entered by user)

<?php
      
if(isset($_GET['save']))
       
{
	
if($_GET['n']%2==0)
	
{
	
echo $_GET['n']." is even number";
	
}
       
}
	 
?>
	
<body>
	
<form method="get">
	   
Enter Your number<input type="text" name="n"/><hr/>	   
	    
<input type="submit" value="check number" name="save"/>
	 
</form>

</body>

Output
10 is even number
Enter Your number

in the above example
we check if statement program
First we create a textbox and a button in a form using HTML script.
in this program we check given number is even or not.
The isset( ) function is used to check existence. $_GET[ ] is used to collect value that is entered by user.
after this if condition check the number is even. if the number enter by user is even. statement is execute, print even number.


WAP to check given number is Positive

Illustrate example to check if given number is greater than 0 then show notification message number is positive.

<?php
	
$num=$_POST['n'];
	
if($num>0)
	 
{
	   
echo $num." is positive number";	
	 
}
	 
?>
	
<body>
	
<form method="post">
	   
Enter Your number<input type="text" name="n"/><hr/>	   
	    
<input type="submit" value="check number"/>
	 
</form>

</body>

Output
10 is positive number
Enter Your number

in the above example First we create a textbox and a button in a form using HTML tags.

in this program we check if number is grater than zero .it show a message "no is positive".

The isset() function is used to check existence.$_GET() function is used collect value that is entered by user.

if the value is grater than 0. then statement will execute and show Message

Find the sum of even number between 1 to 100

<?php
 	
	
$sum=0;
	
for($i=1;$i<=100;$i++)
	 
{
		
if($i%2==0)
		 
{
		
$sum=$sum+$i;
		
}
	
}

echo $sum;

?>

Output 2550

in the above example
whole program are in PHP script. Here we want to sum of even no.
We declare a variable($sum) initialize its value = 0.
For loop is used to check value from 1 to 100. The condition that declare inside the if check the number is even or not.
if the no is even, statement will execute and print sum of all even no those exist between 1 to 100.
Initially $sum value=0. after check the even number condition.it store the even no in variable ( $i) and it sum with ($sum).
again and again it check the even number condition and calculate the sum.


No Sidebar ads