3 ways to use if else statement in php

3 ways to use if else statement in php

PHP is one of the popular web programming language in web world. Many CMS like WordPress, Joomla, Drupal has been written in PHP language. Also popular forum scripts like phpBB, vBuletin developed using PHP. That’s why PHP become a popular web language day by day.

My previous tutorials posted on PHP, I wrote about how to work with array, how to work with string. Hope you learn some new tips and tricks from there. Today I’m going to share something new about how to use if else statement and we will learn 3 different ways to use of If else statement in your PHP based web application.

As you know, like other programming language If else is one of the most frequently used conditional term in PHP. So, as a web developer/programmer you should know how to use the power of if/else statement properly in different situation of your code.

So, lets get started –

– Basic uses of if-else statement:

This is very basic style of if else statement and most of the time used by beginner. Have a look –

if( $i=10 ) {

 echo "My value is ten";

} else {

 echo "Please set a value";

}

 

You can also use nested if-else statement using this style. Have a look-

 

if( $i=20 ) {

 echo "My value is twenty";

} else if( $i=10 ) {

 echo "My value is ten";

} else {

 echo "Please set a value";

}

Very simple!

– Intermediate use of if-else statement:

 

Now, If you are being comfortable with basic styling of if-else statement then it’s time to know second way to use of if-else statement. Have a look-

 

if ($i == 10) :

    echo "My value is ten";

else :

    echo "Please set a value";

endif;

 

We just need to remove curly braces from if and else statement and replace them by colon(:) symbol and also add endif term at the end of the last statement. Most of the time, I can see this type of if-else statement has been used in WordPress theme or WordPress Plugin code.

You can also use nested if-else statement in this style. Have a look-

 

if ($i == 20) :

    echo "My value is twenty";

elseif ($i == 10) :

    echo "My value is ten";

else :

    echo "Please set a value";

endif;

– Advanced use of if-else statement:

 

Final and last technique of using if-else statement is bit tricky and you can’t use them for nested if-else statement. You need to set a condition and two output. That means either it return true or false. Have a look-

  echo ($i == 20)? "It's twenty": "Please set a value";

 

Let me explain the code. This line of code check if value of i is equal to 20 or not. If it equal to 20 that means true, then it echo first text “It’s twenty”. If it false then it echo “Please set a value”. I love this way to check. Because it’s clean and clear.

 

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!Enjoy!

Share It

Related Posts