Saturday, May 21, 2011

PHP Lesson 2: Expressions & Operators

Like many programming languages, PHP deals with expressions (as in, mathematical expressions.) In fact, almost every PHP statement, other than certain "language constructs" (which you will learn about later) is also a mathematical expression.

An expression consists of operators, operands, and sometimes parenthesis (to override the order of operations.) An operator is something like one of these:

+ - * / (meaning plus, minus, times, and divide)

An operand is something that an operator works with. So in the following expression...

3 + 4

... the operator is + and the operands are 3 and 4.

As it turns out, there are a lot more things considered to be operators than just those four basic arithmetic operations. One of the most important operators is "the assignment operator", which is represented by a single equal sign. The assignment operator requires a variable to be specified on the left hand side. The right hand side is evaluated and whatever the answer is is stored into the variable on the left side. In PHP, all variables begin with a dollar sign, and have names which must start with a letter or underscore, and consist of letters, numbers, and underscores.

$myVariable = 3 + 4;

The order of operations deems that assignments happen last. So first, 3 and 4 are added together to get 7, then the 7 is stored into $myVariable. Easy, huh?

PHP lets you make up a new variable on the spot by doing exactly that. Just pick a name you haven't used before, and assign something to it! It's that easy.

Once you've assigned a value to a variable, you may use the variable within other expressions, and you may also choose to reassign it to a different value later. (This is done in exactly the same way as you first assigned it.)

$x = 4;
$y = 10;
$z = $x * $y;
$x = 1;

You should be able to identify the variables, the operators and operands, and tell apart the operands which are numeric literals from those which are references to variables. You should also be able to determine what the value of each of the named variables will be when those four lines of code are finished executing.

So, numbers aren't the only thing PHP can work with. PHP also works with strings of text, as you learned in the Hello World lesson. As it turns out, strings may be used as operands for some of PHP's operators, as well as numbers, and there is even a special operator that is designed exclusively for strings. It is called the concatenation operator and the symbol for it is the period.

$a = "Box";
$b = "Purple";
$c = $b . $a;

To concatenate means to tack one thing onto the end of another. After running the above code, the variable $c will hold the value "PurpleBox" (without any space, because neither of the concatenated variables had a space anywhere in it.)

You can also concatenate literals, by specifying them in quotes, so we could fix the space issue by changing that last line to read:

$c = $b . " " . $a;

Thus we are concatenating the value of variable $b with a blank space (represented as a single space wrapped in quotes), and concatenating that with the value of variable $a. If you try to concatenate a number, PHP automatically converts the number into a string representation of the number in decimal.

Mathematical Operators: Each of these takes two numbers for input and gives a number for output.

-$b ... Opposite. Turns a positive value negative or a negative value positive.
$a + $b ... Addition.
$a - $b ... Subtraction.
$a * $b ... Multiplication.
$a / $b ... Division.
$a % $b ... Modulus (The remainder of integer division)
$a & $b ... Bitwise AND
$a | $b ... Bitwise OR
$a ^ $b ... Bitwise XOR
$a << $n ... Shift the binary value of $a left by $n bits.
$a >> $n ... Shift the binary value of $a right by $n bits.

Logical Operators: Each of these takes two Boolean values for inputs and gives back a Boolean value as an output. See below for rules on what values are considered true or false.

!$a ... Logical NOT
$a && $b ... Logical AND
$a || $b ... Logical OR
$a xor $b ... Logical XOR

Other Operators:

$a = $b ... Assignment.
$a . $b ... Concatenation of Strings.

Comparison Operators: Each of these gives back a Boolean value as an output.

$a == $b ... Is equal to
$a != $b ... Is not equal to
$a > $b ... Is greater than
$a >= $b ... Is greater than or equal to
$a < $b ... Is less than
$a <= $b ... Is less than or equal to
$a === $b ... Is exactly equal to (We will talk about what this means in another post.)
$a !== $b ... Is not exactly equal to (Again, in another post...)

When comparing strings, dictionary order is used to determine lessness or greatness. "z" is greater than "a" and "1000" as a string is less than "12", but the number 1000 is greater than the number 12.

Do all Operators Return Something?

3 + 4 returns 7. But do all the operators return something?

What about $x = 6? Yes, in fact, in addition to storing 6 into $x, it also returns the same value as its own result. Because of this, you can use an odd shortcut like this:

$z = ($x = 6);

This will take the 6, store it in $x, then store the "answer" of $x = 6 into $z. In actuality, the parenthesis here are not needed. I only put them in for clarity to show the sequence of steps.

Is it True or False?

This little section about True and False values might not make a lot of sense yet, but I'm putting it here anyway...

PHP has a way of considering values as true or false even if they are of a type other than boolean. Here are the rules:

A boolean is considered true if it is true, and false if it is false. (I didn't even need to write that!)
A number is considered false if it is zero, but any other number is considered true.
A blank string is considered false, as well as a string containing only the zero character (this way a number after having been converted to a string retains the same true/false value as the original number.) Any other string is considered true.

Order of Operations

So, with so many operators it would be good to have an idea of what the order of operations are so we know when to use parenthesis and when not to. Here it is, in a nutshell, considering all the operators we have learned so far. You don't need to memorize this, just get the general idea of it. Mainly, that its a lot like regular math and that assignment comes last:

First comes ! (not), then multiplication division and modulus (* / %), then addition, subtraction, and concatenation (+ - .), then the bit shifting operators, then comparison operators involving greater than or less than, then comparison operators involving only equality or inequality, then bitwise operators, then logical operators, and finally the assignment operator.

Putting it Together

Please note that I'm not going to be writing the magic PHP tag at the top of each code example (mainly because it is too hard to input angle brackets on blogger,) but it does indeed need to be present at the top of each of your programs...

$name = "Jeff";
$x = 29;
echo $name . " is currently " . $x . " years old.\r\n";
echo "He will be turning " . ($x + 1) . " years old on his birthday.\r\n";

Notice that because addition and concatenation are at the same level of precedence (in the order of operations), I was required to put the $x + 1 in parenthesis so the addition problem would be calculated first and then the answer concatenated onto the string. If I were to forget the parenthesis, $x would get concatenated first, and then an attempt would be made to add the number one to the entire string "He will be turning 29" ... Doing so would end up forcing the string to be converted into a number (since it begins with text and not numeric digits, it ends up getting converted to the number zero), after which the number 1 is added, leaving us with only the answer 1, and finally the concluding string " years old on his birthday.\r\n" would be concatenated onto this 1 (which would first automatically be converted back into a string. So when parenthesis are left out, the result of the entire thing works out to "1 years old on his birthday.\r\n"; and when they are left in the result is "He will be turning 30 years old on his birthday.\r\n";

Next Post: Controlling the Flow of the Program

No comments:

Post a Comment