If you have already register Login here.
if statement in PHP
<?php
if (condition) {
//code to be executed if condition is true;
}
?>
Example 1: Write a program to check even number.(Number entered by user)
<?php
if(isset($_GET["Usersave"]))
{
$numberUser=$_GET["user_number"];
if($numberUser%2==0)
{
echo $numberUser."is even number";
}
}
?>
<html>
<head>
<title>Check even or odd Number</title>
</head>
<body>
<form method="get">
Enter Your number<input type="text" name="user_number"/><br/>
<input type="submit" value="check number" name="Usersave"/>
</form>
</body>
</html>
Output : 10 is Even number
Example 2: Write a program to check the given number is Positive
example to check if given number is greater than 0 then show notification
message number is positive.
<?php
$num=$_POST["unumber"];
if($num>0)
{
echo $num." is positive number";
}
?>
<html>
<head>
<title>Check Positive Number</title>
</head>
<body>
<form method="post">
Enter Your number<input type="text" name="unumber"/><br/>
<input type="submit" value="check number"/>
</form>
</body>
</html>
Output : 10 is positive number
Example 3: Write a program to 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.
© 2025 Easy To Learning. All Rights Reserved | Design by Easy To Learning