In our last Else and Elseif Statement tutorial, we saw an example of the PHP “Is Equal To” operator (==). In this tutorial, I’ll show you the most common PHP operators and what they do.
Operator: ==
Meaning: Is equal to
Example: <?php if (3 == 3) { echo “True.”; } ?>
Notes: In our example, 3 is in fact equal to 3, so our script will output “True.” Be aware of the subtle different between one equal sign (=) and two (==). They mean very different things in PHP. One equal sign is used to assign a value to something, like when you create a PHP variable (Jon: link). Two equal signs are used to ask or tell PHP that one thing is equal to another thing.
Operator: !=
Meaning: Is not equal to
Example: <?php if (3 != 4) { echo “True.”; } ?>
Notes: In our example, 3 is not equal to 4, so our script will output “True.” The exclamation point (!) is used in PHP to ask if something is “not”, so in this case, we’re asking if 3 is NOT equal to 4 by putting the exclamation point in front of the equal sign.
Operator: >
Meaning: Is greater than
Example: <?php if (4 > 3) { echo “True.”; } ?>
Notes: In our example, 4 is greater than 3. Most of us are familiar with the greater than sign (>) from math classes. This is primarily used with numbers. PHP has no personal opinions, no way of inherently knowing if (Brad Pitt > Tom Hanks) is true or not
Operator: <
Meaning: Is less than
Example: <?php if (3 < 4) { echo “True.”; } ?>
Notes: In our example, 3 is less than 4. Again, most of us are familiar with the less than sign (<) from math.
Operator: >=
Meaning: Is greater than or equal to
Example: <?php if (6 >= 5) { echo “True.”; } ?>
Notes: In our example, 6 is greater than 5, so this If Statement is true. We could also say that (5 >= 5) is true, because 5 is equal to 5.
Operator: <=
Meaning: Is less than or equal to
Example: <?php if (7 <= 8) { echo “True.”; } ?>
Notes: In our example, 7 is less than 8, so this If Statement is true. We could also say that (8 <= 8) is true, because 8 is equal to 8.
Operator: &&
Meaning: and
Example: <?php if ($cats && $dogs == “cute”) { echo “True.”; } ?>
Example: <?php if ($cats AND $dogs == “cute”) { echo “True.”; } ?>
Notes: && is another way of saying AND. Both examples above work equally well. Assuming we give our $cats and $dogs variables the value of “cute” (and who wouldn’t), these If Statements return true.
Operator: ||
Meaning: or
Example: <?php if ($cats || $dogs == “cows”) { echo “Woof!”; } ?>
Example: <?php if ($cats OR $dogs == “cows”) { echo “Meow!”; } ?>
Notes: || is another way of saying OR. Both examples above work equally well. Both examples would return false, because neither $cats or $dogs are equal to cows, even if they are very well fed.
Go back to Building PHP Scripts.
Tags: operators, php, programming, tutorial