Here’s a question you probably heard back in elementary school: You’ve got two apples and you find three more, how many apples do you have now? Of course you know the answer, but how do you tell PHP? Of course, you could just hardcode 5—but hardcoded data requires the program to be revised when the data needs to be changed, whereas dynamic variables can be changed from outside of the code and therefore no changes to the code are necessary—in which case, you won’t be able to hard-code a number.
You would have to leave it up to PHP to calculate and use the appropriate value—you just have to know how to tell PHP what you want it to do. As you’ll soon see, doing so is about as simple as typing the expression—the calculation you want PHP to perform—into your code.
Expressions are a combination of operators and operands. An operator is a character that stands for a mathematical operation—such as addition or subtraction. The operand is one of the numbers involved in the operation. For example, if you multiple 5×2, 5 and 2 are both operands.
TIP
Think of the operator as the action in an expression and the operand as the thing the action is being performed on.
An expression may be constructed with anything from just two operands and one operator to an infinite number of operands and operators. The following example shows a simple expression:
1 + 2
This is about as simple as an expression gets. It’s not too intimidating to look at 1 + 2 and know that the result is 3. However, longer expressions can be intimidating. Take a look at the following expression to see what I mean:
1 + (4 * 4 % 6 – 5) / 2
That expression really isn’t as cryptic as it looks. By the end of this chapter, you will not only be able to read expressions such as this one without being intimidated, but you will also be able to write them without much, if any, difficulty.
In the following sections, you will learn about the operators used in this expression. You will also learn that an intimidating expression such as this can be broken down into a few smaller, simpler expressions like the expression 1 + 2 we looked at before.
The following Table 4.1 summarizes PHP arithmetic operators. For now, glance over them and continue reading. You don’t need to try to memorize them—you will have plenty of time to memorize them individually as they are explained. If you need to come back later to refresh your memory, this table may be a good place to start.
Table 4.1. PHP’s Arithmetic Operators Perform Basic Mathematical Tasks Operator Operation Name Example
+ (Unary) Positive +5
- (Unary) Negative -5
+ Plus 5 + 5
- Minus 5 - 5
* Multiply 5 * 5
/ Divide 5 / 5
% Modulus/Remainder 5 % 5
The sections that follow will discuss the operators used within expressions one by one. Each section will leave you with a clear understanding of what exactly each operator does along with how to use it.
Positive and Negative Numbers
While most of your calculations will probably involve only positive numbers, you are sure to encounter negative numbers at some time or another. Negative numbers really don’t have anything special about them. They behave just as they should mathematically, and they have a negative sign preceding them when outputted.
To specify that a number is negative, you must place a negative sign before it. Here are several examples of negative numbers being assigned to $someVar:
$someVar = -2;
$someVar = -64;
$someVar = -1028;
The positive sign is also allowed in PHP, but it serves no useful purpose other than demonstrating to the programmer that a number is positive. Numbers without a sign are automatically positive, however, so the positive sign is rarely used. Here are a few examples of it for your reference:
$someVar = +2;
$someVar = +64;
$someVar = +1028;
CAUTION
While it might seem logical to force a variable’s sign (negative or positive) to be positive by preceding it with the positive sign, this will not work. To reverse a variable’s sign, you must negate it.
Unary and Binary Operators
The positive and negative signs are considered to be unary operators—that is, operators that only require one operand. These are the only two unary operators we’ll discuss in this chapter, although ++ and –, which will be introduced in Chapter 8, “Using while and do-while,” are also unary operators. All of the other arithmetic operators require two operands. For this reason, they are called binary operators.
TIP
For a quick example, consider any addition, subtraction, multiplication, or division problem. In order to perform one of these operations, you must have two numbers—one that will go on the left side of the operator and one that will go on the right. Thus, multiplication (or any other binary operation) cannot be done with only one operand.
If you have trouble understanding why the positive sign doesn’t force the value of a variable to be positive, consider the actual inner workings of these operators:
The negative operator yields the value of its operand times negative one.
The positive operator yields the value of its operand times positive one, or simply the value of the operand; thus, the positive unary operator is essentially ignored.
If you are familiar with binary numbers, don’t be confused by the term binary used in conjunction with binary operators. The word binary has nothing to do with the numbers used as operands; rather, the word binary is used to describe them because they take two arguments.
The rest of the operators in this chapter, including addition, subtraction, multiplication, division, modulus, and the compound operators, are all binary operators.
Addition
Addition is done using the plus character found on your keyboard. Let’s return to the scenario presented at the beginning of this chapter about apples—you have two apples and you find three more. This could be coded as
<?= 2 + 3 ?>
That’s pretty simple: The expression 2 + 3 is placed inside short equals tags. PHP always handles mathematical expressions before doing anything with them—after all, the point of the expression is to calculate a result. Thus, the output will be the expression’s result, 5.
CAUTION
Don’t let the equals sign in the short equals tag confuse you—the addition operation has nothing to do with the equals sign because the equals sign is part of the tag.
To clarify this even further, the equals sign isn’t part of an assignment. Instead, it is part of the method of output being used. Thus, even though it looks like an assignment or mathematical sort of operator, it is actually part of the tag signaling PHP’s output.
This example is presented in a short equals tag for simplicity; you could use any number of alternatives, or even store the result to another variable. The important thing to understand is that placing a plus sign between two values tells PHP to add the two.
Now, let’s make the preceding code dynamic so it can work with any two numbers. Following the previous scenario, those numbers will be the number of apples you had and the number of apples you found. Let’s assume that the number of apples you had is stored in $applesHad and the number of apples you found is stored in $applesFound. To get the result depending on these two variables, you would use the following expression:
<?= $applesHad + $applesFound ?>
No matter what two values are stored in these variables, the output will always be the result of this expression—their sum.
CAUTION
Dealing with very large numbers in computers can sometimes be difficult. Since the computer has to store numbers as a fixed-length set of ones and zeros, numbers can only be a certain size (going either direction—positive or negative) before they get too big and their value becomes inaccurate. Although, it depends on the operating system and hardware of the machine running PHP, the range of numbers that can accurately be stored is usually from –2,147,483,648 to +2,147,483,648 (2 to the 31st power, which is the case for a 32-bit system).
Subtraction
Subtraction works the same way as addition—however, the operator used is now the minus sign on the keyboard. Let’s reverse our scenario: You have five apples but you drop two. In numeric terms, this would be expressed as
<?= 5 - 2 ?>
To make that calculation dynamic, we replace the numbers with variables. Let’s assume that $applesHad is the number of apples we had to start with and that $applesDropped is the number of apples that were dropped. So, following with this example, $applesHad is 5 and $applesDropped is 2. To output the remaining number of apples, we use the following code:
<?= $applesHad - $applesDropped ?>
TIP
Since this program uses variables within its calculations, we could get these variables from input. Upon returning the result to the user, we’ve created a calculator—a calculator that only subtracts, but a calculator nonetheless.
Multiplication
Multiplication works just as addition and subtraction did using the asterisk as the operator.
The following demonstrates a multiplication expression:
<?= 2 * 4 ?>
NOTE
A space was added on either side of the asterisk to promote readability. This lessens any possible confusion about what’s going on in this statement. It is a good idea to pad all operators (except the two unary operators) in this way.
Using the asterisk instead of x avoids the conflicts that could arise. For example, the letter x could appear in any variable or constant name. The following code illustrates this point:
<?= $varOnex$varTwo ?>
This code is impossible even for a human to decipher definitively. The code could mean “$varOne times $varTwo” or it could mean “$varOnex followed by $varTwo.”
To get around this, PHP uses a character that cannot show up in a variable name: the asterisk. The asterisk makes a likely pick: It’s in use on numeric keypads, calculators, and in some other places already.
The following code changes the previous example so that it will mean what we want it to mean—”$varOne times $varTwo”:
<?= $varOne * $varTwo ?>
CAUTION
If you are familiar with algebraic notation (such as “3x”), you should note that placing two variables or a number and a variable next to each other does not imply multiplication. In other words, if you intend to multiply a variable by three, you must separate the number three from the variable with an asterisk. Not doing so (using 3$someVar) will cause PHP to terminate with an error.
Division
Now it’s time to take a look at the last of the four common operators—the division operator. You may already be used to seeing fractions expressed all on one line; if you’re not, it’s not too hard to learn. Instead of stacking the numerator over the denominator vertically, you must put them on one line separated with a slash. The slash, in this case, is the operator.
To divide 35 by 7, the following expression could be used:
<?= 35 / 7 ?>
This code would output 5.
As with the other arithmetic operators, this can be used with variables. To divide $varOne by $varTwo, you might use
<?= $varOne / $varTwo ?>
CAUTION
You must check to make sure your denominator is not 0 before you perform the operation (checking for certain conditions will be discussed when we get to if in Chapter 6, “The if, elseif, and else Statements”). A denominator of zero yields an undefined result, to and PHP will terminate with an error informing you that you have attempted to divide by zero.
Modulus Division
This is one you to probably haven’t seen before—at least not with this name. This operator is less commonly called the remainder operator—and it does just that. The modulus operator was created to allow you to easily get the remainder resulting from the division of two integers.
A simple example of modulus division follows:
<?= 10 % 3 ?>
The output of this statement is 1—three goes evenly into ten three times with a remainder of one. The following example also demonstrates this concept:
<?php
$numerator = 5; S/B 9 to match text below.
$denominator = 9; s/b 5 to match text below.
?>
Regular division: <?= $numerator / $denominator?>
Integer division: <?= (int)( $numerator / $denominator) ?> r<?= $numerator % $denominator
?>
First, nine is divided by five. Then, 9 is divided by 5 and the result is typecast to an integer to get only the number of times that 9 divides into 5 evenly, resulting in 1. The remainder is then expressed using modulus division and is output after the “r.”
The output is
Regular division: 1.8
Integer division: 1 r4
TIP
Modulus division is sometimes referred to simply as mod. Expressions are commonly read this way; for instance, the remainder calculation in the previous example is read “nine mod five.” It is shorter and easier to read an expression this way than reading the whole phrase “the remainder of nine divided by five.”
CAUTION
Attempting to use modulus division on a floating-point value is strongly discouraged. Any offending values (values that are not integers) will be typecast to integers and any decimal values will be truncated. On top of that, PHP will not terminate because of this problem because it is corrected by the type casting. Only use modulus division on a value that may be a floating-point value if you are fully aware that the value will be typecast to an integer before being evaluated with the operator.