Logic and Operators

PHP supports a wide range of operators. The complete set can be found by searching the PHP manual. If you go to the manual online, you’ll find that operators have their own section in the language reference portion:

{show the cursor using the PHP manual online – documentation -> English -> Operators}

I’m going to cover just 4 types of operators in this video, but if you want to learn more, they’re covered very well in the online manual.

The first set of operators we’re going to cover are the arithmetic operators. These include the familiar operators for addition, subtraction, multiplication, and division, plus 2 others – negation and modulus. The multiplication sign in PHP is the asterisk character ‘*’, and the division sign is the forward slash ‘/’. If you use division on two integers that don’t divide evenly, your result will be a float. However, if you use division on two ints that do divide evenly, your result is an int. This is worth pointing out, because in some languages, dividing ints just cuts off anything after the decimal in order to keep the result as an int. And in some other languages, they’ll cast the result of an integer division to a float no matter whether they divide evenly or not. The PHP engineers decided on a middle way.

As for negation, it’s just the minus sign in front of a variable to get its sign opposite. So, in the expression:

$a = 5;
$b = -$a;

$b becomes -5. And:

$c = -$b;

$c becomes 5.

Modulus is just a little more complicated. It’s used to find the remainder left over from dividing two numbers. So for instance:

$a = 25 % 3;

The way this works is you take 25 and subtract as many 3’s as you can without going negative. Whatever is left is the result of your expression. In this case, that’s 25-24, which is 1. So $a has a value of 1. Now, if the first number in your expression had been ‘-25’ your result would be -1. Although, oddly enough, the sign of the number after the modulus operator makes no difference to the sign of the result. So if it had been 25 % -3 the value of the expression would still be a 1.

As far as operator precedence goes, negation has the highest precedence. Multiplication, division, and modulus all have the same precedence. And addition and subtraction together have the lowest precedence. Don’t dwell too much on it right now though, since we tackle PHP’s ability to do math in a later chapter. I’m only introducing this now because it’s just handy to be able to do a little basic arithmetic here and there in your everyday scripts.

The next type of operator we’re going to look at is the assignment operator. The basic assignment operator is just the ‘=’ sign, as we’ve already seen in previous videos. It simply assigns the value of the expression to the right of the equal sign to a variable of some sort on the left side.

There are other assignment operators though. They all boil down to something like ‘Perform an action on the variable to the left and then assign the result of that expression back to the left-hand variable.’

So, for instance, there’s an operator for incrementing your variable by some amount. Now, you could write:

$a = $a + 5;

Since it evaluates the right-hand side first, the value of $a is incremented by 5. However, PHP provides another way to do the same thing in a sort of short-hand:

$a += 5;

PHP also has assignment operators for subtraction, multiplication, division, and modulus:

$a -= 5; //produces the exact same result as $a = $a – 5;
$a *= 3; //produces the exact same result as $a = $a * 3;
$a /= 2; //produces the exact same result as $a = $a / 2;
$a %= 8; //produces the exact same result as $a = $a % 8;

If all you need is to increment or decrement a variable’s value by one, PHP supports another, even shorter, short-hand:

$a++; //identical to $a += 1 and $a = $a + 1
$a–;  //identical to $a -= 1 and $a = $a – 1

The next type of operator we’ll look at are the comparison operators. These are the ones that you use when you want to compare two expressions in some way, and arrive at a value for the combined expression of either true or false.

When you want to determine whether two expressions are alike, PHP provides both an equality comparison and an identity comparison. The difference is important. For an equality test, the operator is two equal signs next to each other, like this:

$a == $b;

If $a and $b have the same value, the expression returns true. But they may not be the same thing. For instance:

$a = 1;
$b = ‘1’;
$c = $a == $b; //$c is true, because converting 1 to a string produces ‘1’ and converting ‘1’ to an int produces 1

In this case $c will hold the value ‘true’, because that’s the result of the equality test. But if we change to the identity test, which consists of 3 equal signs together, we’ll get false, because the identity test checks both the value and the type:

$c = $a === $b; //$c is now false because while they have the same value, $a and $b are not of the same type

This test is particularly useful when, for instance, a function might return 0 or false, and you need to be  sure you know which one you got back. For instance, PHP provides a useful built in function called strpos. It searches one string for the first occurrence of another. If it finds that search term at the very beginning of the searched string, it returns a 0. But if it doesn’t find the term at all, it returns the boolean false. Just testing for == false would be a recipe for trouble down the line.

Now, the counterpart to the equality and identity operators are the inequality and non-identity operators. These are an exclamation point followed by an equal sign, and an exclamation point followed by two equal signs, respectively.

$a != $b; //test for different value
$a !== $b; //test for different value or type

This has different meanings for different types. A string and an int can be equal if they have the same quoted value. But a string and an int can never be identical, because they’re of different types. If two ints are equal, they are also identical. And the same is true for strings and booleans. However, for arrays, two arrays are equal if they have the same key/value pairs. But those values can be of different types so long as they pass an equality test with each other. Two arrays are only identical if they have identical key/value pairs (meaning types are also the same), and with all key/value pairs in the same order.

The remaining comparison operators are the greater than/less than operators:

$a < $b; //test whether $a is less than $b
$a > $b; //test whether $a is greater than $b
$a <= $b; //test whether $a is either less than or equal to $b
$a >= $b; //test whether $a is greater than or equal to $b

With ints, the comparison is obvious enough. You’re just checking basic math. With strings, you’r checking them alphabetically, so a string starting with an ‘a’ would be considered less than a string starting with a ‘b’. However, the comparison is also case-sensitive. So a string beginning with lower-case ‘a’ would be considered greater than a string beginning with an upper-case ‘B’. If you need to compare strings in a case-insensitive way, PHP provides some built in functions to do that. We look at those more in another chapter.  With booleans, ‘false’ is less than ‘true’. And with arrays, well, it gets difficult to explain, and it’s not something you’re likely to need to do anyway.

The last operators we’re going to take a quick look at are the logical operators. And we’re only going to look at 3 of them. These are called logical operators because they’re supposed to be used with boolean logic expressions. The first, is the ‘not’ operator. It’s just a single exclamation point places in front of that expression, and all it does is flip the expression. If the expression had been true before, with the not operator it becomes false. And if it had been false before, the not operator makes it true.

The second operator is the ‘and’ operator. It consists of 2 ampersands together. You use it to string two boolean expressions together. If they were both true, the entire combined expression becomes true. But if either or both expression had been false, the combined expression is false.

$a = true && false; //evaluates to false
$a = true && true; //evaluates to true

The way the PHP engine works is by evaluating statements from left to right. If the left expression is false, it doesn’t even bother to evaluate the right-hand expression. It just returns false and skips the code to the right. You can prove this is the case by putting some code to the right that ought to cause some sort of run-time error, and code to the left that will evaluate to false:

false && array() + 5; //$a is false – no error
true && array() + 5; //throws a fatal error for unsupported operand types

The counterpart to the and operator is the or operator. It consists of two vertical bars ‘||’. If an expression on either side of the or operator evaluates to true, then the entire expression is true:

true || false; //evaluates to true
false || false; //evaluate to false

And just like the and operator will stop evaluating an expression if the first half is false, the or operator will stop evaluating an expression if the first half is true. In that case it just returns true and the second half of the expression is simply ignored.

Those are all the operators I wanted to cover in this video, but there are plenty more provided by PHP. You won’t need them to complete any of the exercises at the end of this chapter, but if you want to learn them just in case you need them in the future, as always, I refer you back to the PHP manual.

{show website http://us2.php.net/manual/en/language.operators.php}

February 07 2010 04:44 pm | Basics and PHP Programming Basics and PHP tutorial scripts

Comments are closed.