|
Free
PHP Tutorials
|
![]() |
home |
Stay
at Home and Learn
|
|||||||
PHP Tutorials |
||||||||
|
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. |
|||||||
| Operand | Example | Meaning | ||||||
| && | $variable1 && $variable2 | Are both values true? |
||||||
| | | | $variable1 | | $variable2 | Is at least one value true? | ||||||
| AND | $variable1 AND $variable2 | Are both values true? | ||||||
| XOR | $variable1 XOR $variable2 | Is at least one value true, but NOT both? | ||||||
| OR | $variable1 OR $variable2 | Is at least one value true? | ||||||
| ! | !$variable1 | Is NOT something | ||||||
|
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. The &&
Operator $username ='user'; if ($username ='user' &&
$password ='password') { 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. The | | Operator $total_spent =100; if ($total_spent =100 |
| $special_key ='SK12345') { 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. AND and OR $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! XOR $contestant_one = true; if ($contestant_one XOR
$contestant_two) { See if you can guess which of the two will print out, before running the script. The ! Operator $test_value = false; if ($test_value = = false) { 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 --> <--Back to the PHP Contents Page View all our Home Study Computer Courses
|
||||||||