SakhaliaNetHome PageMilitary HistoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Logical operators

PHP Example #24

Negation operator

The negation operator (not) is useful for negating any value. A value that is true will become false when combined with the negation operator, and the opposite is true as well. Placing the operator ! before an expression is like checking if the expression is false, instead of checking if it is true. The two if statements in the example are equivalent.

<?php
$finished = false;
// ($finished == false) All the checking expression is true if $finished is false
if ($finished == false) {
print 'Not done yet!';
}
print nl2br("\n\n");
// (! $finished) All the checking expression is true if $finished is false
if (! $finished) {
print 'Not done yet!';
}
print nl2br("\n\n");
$first_name = 'AishA';
$last_name = 'aisha';
if (! strcasecmp($first_name, $last_name)) {
print "$first_name and $last_name are equal.";
} else {
print "$first_name and $last_name are not equal.";
}
?>
Not done yet!

Not done yet!

PHP Example #25

Negation operator

In this example the negation operator is combined with the strcasecmp() function, which compares two strings and returns 0 (a false value) when both strings are identical, regardless of uppercase or lowercase letters.

<?php
$first_name = 'AishA';
$last_name = 'aisha';
if (! strcasecmp($first_name, $last_name)) {
print "$first_name and $last_name are equal.";
} else {
print "$first_name and $last_name are not equal.";
}
print nl2br("\n\n");
$first_name = 'AishA';
$last_name = 'aisha';
if (strcasecmp($first_name, $last_name)) {
print "$first_name and $last_name are equal.";
} else {
print "$first_name and $last_name are not equal.";
}
?>
AishA and aisha are equal.

AishA and aisha are not equal.

PHP Example #26

Logical operators

By using logical operators, multiple expressions can be evaluated by an if() statement. The operator && (AND) checks if both expressions are true, while the operator || (OR) checks if anyone of them is true.

<?php
$age = 25;
if (($age >= 13) && ($age < 65)) {
print "You are too old for a kid's discount and too young for the senior's discount.";
}
print nl2br("\n\n");
$meal = 'breakfast';
if (($meal == 'breakfast') || ($dessert == 'souffle')) {
print "Time to eat some eggs.";
}
?>
You are too old for a kid's discount and too young for the senior's discount.

Time to eat some eggs.