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 properly as well efficiently of the if/else statement in different situation 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 if else statement, and we are going to learn three different ways to use of it in a PHP based web application. So, let’s 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"; }
– 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’s explain the code. This line of code check if value of i is equal to the number 20 or not. If it is then the statement is true. So, it will echo first text “It’s twenty”. One the other hand, If it false then it echo “Please set a value”. If you want to write clean and readable code then I suggest you to use this technique.
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!