Three ways to use if else statement in php

3 ways to use if else statement in php

If else is one of the most frequently used conditional statements in PHP. For that reason, Web programmers should know and have a clear idea about how to use appropriately as well as efficiently the if/else statements in different situations of a project.

In our previous tutorials on PHP, I wrote about how to work with array and how to work with string. I hope you read and enjoyed them.

As a continuation of a series tutorial on PHP, today I am going to write about how to use the if-else statement, and we are going to learn three different ways to use it in a PHP-based web application. So, let’s get started.

– Basic uses of if-else statement:

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

if( $i=10 ) {
 echo "My value is ten";
} else {
 echo "Please set a value";
}

You can also use nested if-else statements 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";

}

– Intermediate use of if-else statement:

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

if ($i == 10) :

    echo "My value is ten";

else :

    echo "Please set a value";

endif;

We need to remove curly braces from if and else statements and replace them with a colon(:) symbol and also add an 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 themes or WordPress Plugin code.

You can also use nested if-else statements 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’s explain the code. This line of code checks if value of i is equal to the number 20 or not. If it is, then the statement is  true. So, it will echo the first text “It’s twenty”. On the other hand, If it false, then it echoes, “Please set a value”. If you want to write clean and readable code, I suggest using this technique.

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

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top