Inverting Statements in If-Else
Consider the following code:
<?php
if ($num > 0 and $num < 5) {
echo '+++';
} else {
echo '---';
}
?>
Let's invert the condition from the given code, that is, turn it into its opposite. The opposite condition will be as follows:
<?php
if ($num <= 0 or $num >= 5) {
echo '+++';
} else {
echo '---';
}
?>
As you can see, inverting a condition
requires some thought. It is much
easier to use the ! operator,
which represents a logical NOT.
Using this operator, we just need
to put an exclamation mark before the initial
condition - and it will invert itself:
<?php
if ( !($num > 0 and $num < 5) ) {
echo '+++';
} else {
echo '---';
}
?>
The following code is given:
<?php
if ($num1 >= 0 or $num2 <= 10) {
echo '+++';
} else {
echo '---';
}
?>
Using the ! operator, invert
the given condition.