Shorthand If in If-Else Construct
Let's say, for example, we want to know if
the variable $test is equal to true.
In this case, the if construct
can be written like this:
<?php
$test = true;
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>
When programming, such checks are required
very often, so there is a more
elegant shorthand form for them: instead of if ($test
== true) you can simply write if
($test).
Let's rewrite our code in the shorthand form:
<?php
$test = true;
if ($test) { // equivalent to if ($test == true)
echo '+++';
} else {
echo '---';
}
?>
Now suppose we are checking that the variable
$test is not equal to true:
<?php
$test = true;
if ($test != true) {
echo '+++';
} else {
echo '---';
}
?>
In this case, the shorthand syntax will look like this:
<?php
$test = true;
if (!$test) { // use logical NOT
echo '+++';
} else {
echo '---';
}
?>
A similar shorthand exists for checking
for false. Suppose we have the following code:
<?php
$test = true;
if ($test == false) {
echo '+++';
} else {
echo '---';
}
?>
The condition $test == false is actually
the same as $test != true:
<?php
$test = true;
if ($test != true) { // equivalent to if ($test == false)
echo '+++';
} else {
echo '---';
}
?>
Well, we already learned how to shorten such a condition in the previous example. Let's shorten it:
<?php
$test = true;
if (!$test) {
echo '+++';
} else {
echo '---';
}
?>
Rewrite the following code using shorthand comparison:
<?php
$test = true;
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>
Rewrite the following code using shorthand comparison:
<?php
$test = true;
if ($test == false) {
echo '+++';
} else {
echo '---';
}
?>
Rewrite the following code using shorthand comparison:
<?php
$test = true;
if ($test != true) {
echo '+++';
} else {
echo '---';
}
?>
Rewrite the following code using shorthand comparison:
<?php
$test = true;
if ($test != false) {
echo '+++';
} else {
echo '---';
}
?>