Home » Web development » PHP » How to use if else condition in php

How to use if else condition in php

if else condition in php

  • PHP programming like other languages have the conditional statement processing also.Conditional statement add intelligence to our scripts.
  • This gives us the functionality to perform various command based on various conditions
  • We will be working on if/then/else statement in this post i.e if else in php

The basic format for the if/then/else conditional statement processing is

if <condition>
{
commands
}
else
{
commands
}

A Example would be

if ($name = “ ” )
{
echo “name is empty”';
}
else
{
echo “name is $name”;
}

It is also possible to create compound conditional statements by using one or more else if (elif) clauses. If the first condition is false, then subsequent elif statements are checked. When an elif condition is found to be true, the statements following the associated then statement are executed.

if condition
{ commands}
elif condition
{commands}
else
{ command}

Example

if ($x < "1000") {
echo "you are awesone!";
} elseif ($x < "2000") {
echo "You are good!";
} else {
echo "You are bad!";
}

Algorithm for if else in php

The if statement uses the exit status of the given condition

if test condition
{
commands (if condition is true)
}
else
{
commands (if condition is false)
}

if statements may be nested

if  conditions
{commands}
else if conditions
{commands}
else
{commands}

Various operators which are used in condition

OperatormeaningExampleOperator Result
==Equal$a == $bReturns true if $x is equal to $y
===Identical$a === $bReturns true if $x is equal to $y, and they are of the same type
!=Not equal$a != $bReturns true if $x is not equal to $y
<>Not equal$a <> $bReturns true if $x is not equal to $y
!==Not identical$a !== $bReturns true if $x is not equal to $y, or they are not of the same type
>Greater than$a > $bReturns true if $x is greater than $y
<Less than$a < $bReturns true if $x is less than $y
>=Greater than or equal to$a >= $bReturns true if $x is greater than or equal to $y
<=Less than or equal to$a <= $bReturns true if $x is less than or equal to $y

And and OR operator


we can test multiple test condition with && and || operator

See also  PHP array functions

&& – this stand for and condition

($1 == yes)  && ( $2 ==yes)

So both the condition need to be true for this whole expression to be true

|| – This stand for or condition

($1 == yes)  || ( $2 ==yes)

Only one condition need to be true for this whole expression to be true.

Hope you like this post . Please do provide the feedback

Also Reads
Define constant in PHP
PHP Array functions
PHP String Functions
PHP Manual

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top