The power of any programming language is all about making decisions based on user selection. Conditional operators (conditional statements) execute code only when certain condition is met. If the expressions inside the parentheses () evaluate to true, the code between braces {} is executed. If it is false, then the code between braces is skipped. It’s worth mentioning that the code which follows the closing brace } is executed in any case, ‘coz it’s not part of the conditional statement. Since the same principle is used throughout all programming languages, you can learn it in the PHP context and the apply the same skils, say, in JavaScript. Ain’t it cool?
Let’s take a looksie at our first example:
if ( expression ) {
// Run this code
}
Here are some examples you can play with, try increasing/decreasing the value of the $students variable to get the idea of how it works
$students = 26;
if ($students > 25){
echo 'You can see this text because there are more than 25 students';
}
if ($students == 26){
echo 'There are exactly 26 students in the group';
}
And a bit more complex example:
if ($students >= 20 && $students <= 30){
echo 'There are between 20 and 30 students in the group';
}
In the last code example, we have two conditions that should be met – the value of the $students variable should be greater or equal to 20 AND should be less or equal to 30. Note: if either of those conditions evaluate to FALSE, then the code won’t be executed.
We can also place hte 'if' statement inside another 'if" statement. Here’s the last code example rewritten :
if ($students >= 20){
if ($students <= 30){
echo 'There are between 20 and 30 students in the group';
}
}
You can also place as many lines of code between the braces as you need:
if ($students > 20){
echo 'True';
echo 'Definitely True';
}
By the way, if you have just one line of code between the braces then you can omit them, like this
if ($students > 20)
echo 'True';
But from my personal experience it’s better to write the braces as the code might become a bit confusing when there’s more code to follow the statement.
Thats' about it what I can tell you about conditional operators, guys.
And one more thing, if you know that your followers or friends may like this info, don't hesitate to like, tweet and Google+ the post. Thanks 🙂