In our first section, we talked about the multiple ways that you can use the equals sign to assign variables or compare them, based on value and type. In part 2 of this series, we are going to dive deeper into the comparison operators, and exactly how they function. There is a lot of basic programming concepts here, but where better to start than the basics.
Starting off, we will look at the greater than and less than operators, which are going to be extremely simple and to the point.
$a = 1; $b = 2; $result = $a > $b; echo "a > b = "; echo $result; echo "
"; $result = $a < $b; echo "a < b = "; echo $result;
The above lines of code will output that "a > b = false" (false doesn't echo), and "a < b = true". What does this mean? It means that the values returned by greater than and less than statements are either true or false. The above would be an extremely strange way of finding your results, so I am going to use a more common example next.
if($a > $b) {
echo "a is greater than b";
} else {
echo "a is less than b";
}
Essentially what you are saying, is IF A is greater than B, then display the echo, else move on down to the bottom portion. Pretty simple, so moving on, here are two new operators.
if($a >= $b) { }
if($a <= $b) { }
It's just what it looks like, greater than OR equal to. Now your mixing and matching operators, stating maybe that you want something above/equal to, or less than/equal to. It's extremely simple logic/algebra here, just to check the values of these variables.
Onto a little something more complicated, the not operator.
$a = 1;
$b = 2;
if($a != $b) { echo "not equal"; }
The exclamation point in front of the equals means we are making sure they are not the same value. This is extremely useful when you are building something that cannot have identical values. The "!=" statement checks the two variables to make sure they are not equal to each other, but does not care whether or not they are the same data type. Get where this is going from the "triple equals" from the first article?
$a = 1;
$b = "1";
if($a !== $b) { echo "not equal or not the same type"; }
By using the single exclamation and the double equals, it is now also checking the variable types to make sure they are not the same. Even though technically both of the variables are equal to 1, $b is a string, and $a is an integer, so this statement will return and tell you they are "not equal or not the same type".
Well, these are all the basic operators. The next set of operators won't come up until the more advanced articles, where we will talk about Ternary Operators.
