Home and Learn: PHP Programming Course
As well as the PHP comparison operators you saw earlier, there's also something called Logical Operators. You typically use these when you want to test more than one condition at a time. For example, you could check to see whether the username and password are correct from the same If Statement. Here's the table of these Operands.
The new Operands are rather strange, if you're meeting them for the first time.
A couple of them even do the same thing! They are very useful, though, so here's
a closer look.
$username ='user';
$password ='password';
if ($username =='user' && $password =='password') {
print("Welcome back!");
}
else {
print("Invalid Login Detected");
}
The if statement is set up the same, but notice that now two conditions are being tested:
$username =='user' && $password =='password
This says, "If username is correct AND the password is ok, too, then let them in". Both conditions need to go between the round brackets of your if statement.
$total_spent =100;
$special_key ='SK12345';
if ($total_spent ==100 | | $special_key =='SK12345') {
print("Discount Granted!");
}
else {
print("No discount for you!");
}
This time we're testing two conditions and only need ONE of them to be true.
If either one of them is true, then the code gets executed. If they are both
false, then PHP will move on.
$username =='user' && $password =='password
With this
$username =='user' AND $password =='password
And this:
$total_spent ==100 | | $special_key =='SK12345'
With this:
$total_spent ==100 OR $special_key =='SK12345'
It's up to you which you use. AND is a lot easier to read than &&. OR is a lot easier to read than ||.
The difference, incidentally, is to do with Operator Precedence. We touched
on this when we discussed variables, earlier. Logical Operators have a pecking
order, as well. The full table is coming soon!
$contestant_one = true;
$contestant_two = true;
if ($contestant_one XOR $contestant_two) {
print("Only one winner!");
}
else {
print("Both can't win!");
}
See if you can guess which of the two will print out, before running the script.
The ! Operator
This is known as the NOT operator. You use it test whether something is NOT
something else. You can also use it to reverse the value of a true or false
value. For example, you want to reset a variable to true, if it's been set to
false, and vice versa. Here's some code to try:
$test_value = false;
if ($test_value == false) {
print(!$test_value);
}
The code above will print out the number 1! (You'll see why when we tackle
Boolean values below.) What we're saying here is, "If $test_value is false
then set it to what it's NOT." What it's NOT is true, so it will now get
this value. A bit confused? It's a tricky one, but it can come in handy!
In the next part, we'll take a look at Boolean values.
<-- Back One Page | Move on to the Next Part -->
Email us: enquiry at homeandlearn.co.uk