O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Operator Concepts

PHP has many types of operators. The categories are:

  • Arithmetic operators

  • Array operators

  • Assignment operators

  • Bitwise operators

  • Comparison operators

  • Execution operators

  • Incrementing/decrementing operators

  • Logical operators

  • String operators

The operators are listed as found on http://www.zend.com/manual/language.operators.php. There are some operators we're not going to discuss in order for you to get up and running with PHP as quickly as possible. These include some of the casting operators that we'll just skim the surface of, for now. When working with operators, there are four aspects that are critical:

  • Number of operands

  • Type of operands

  • Order of precedence

  • Operator associativity

The easiest place to start is by talking about the operands.

Number of Operands

Depending on which operator you are using, it may take different numbers of operands. Many operators are used to combine two expressions into a more complex single expression; these are called binary operators. Binary operators include addition, subtraction, multiplication, and division.

Other operators take only one operand; these are called unary operators. Think of the negation operator (-) that multiplies a numeric value by -1. The auto-increment and -decrement operators described in Chapter 3 are also unary operators.

A ternary operator takes three operands. The shorthand for an if statement, which we'll talk about later when discussing conditionals, takes three operands.

Types of Operands

You need to be mindful of the type of operand an operator is meant to work on, because certain operators expect their operands to be particular data types. PHP attempts to make your life as easy as possible by automatically converting operands to the data type that an operator is expecting. But there are times that an automatic conversion isn't possible.

Mathematical operators are an example of where you need to be careful with your types. They take only numbers as operands. For example, when you try to multiply two strings, PHP can convert the strings to numbers. While "Becker" * "Furniture" is not a valid expression, it returns zero. Because the strings don't contain simple numbers, an expression that is converted without an error is "70" * "80". This outputs to 5600. Although 70 and 80 are strings, PHP is able to convert them to the number type required by the mathematical operator.

There will be times when you want to explicitly set or convert a variable's type. There are two ways to do this in PHP—first, by using settype to actually change the data type, or second, by casting, which temporarily converts the value. PHP uses casting to convert data types. When PHP does the casting for you automatically, it's called implicit casting. You can also specify data types explicitly, but it's not something that you'll likely need to do.

Tip

PHP uses implicit casting to the type that the operator requires.

The cast types allowed are:

(int), (integer)

Cast to integer

(bool), (boolean)

Cast to Boolean

(float), (double), (real)

Cast to float

(string)

Cast to string

(array)

Cast to array

(object)

Cast to object

To use a cast, place it before the variable to cast, as in Example 4-2. The $test_string variable contains the string "1234".

Example 4-2. Casting a variable

$test=1234;
$test_string=(string)$test;

Keep in mind that it may not always be obvious what will happen when casting between certain types. You might run into problems if you don't watch yourself when manipulating variable types.

Some binary operators such as the assignment operators have further restrictions on the lefthand operand. Because the assignment operator is assigning a value to the lefthand operator, it must be something that can take a value such as a variable. Example 4-3 demonstrates good and bad lefthand expressions.

Example 4-3. Lefthand expressions

3 = $locations; // bad - a value can not be assign to the literal 3
$a + $b = $c; //bad - the expression on the left isn't one variable
$c = $a + $b; //OK
$stores = "Becker"." "."Furniture"; // OK

Tip

There is a simpler way to remember this. The lefthand expression in assignment operations is known as an L-value. L-values in PHP are variables, elements of an array, and object properties. Don't worry about object properties.

Order of precedence

The order of precedence of an operator determines which operator processes first in an expression. For instance, the multiplication and division process before addition and subtraction. You can see a simplified table at http://www.zend.com/manual/language.operators.php#language.operators.precedence.

If the operators have the same precedence, they are processed in the order they appear in the expression. For example, multiplication and division process in the order they appear in an expression, because they have the same precedence. Operators with the same precedence can occur in any order without affecting the result.

Most expressions do not have more than one operator of the same precedence level, or the order in which they process doesn't change the result. As shown in Example 4-4, when adding and subtracting, it doesn't matter whether you add or subtract first—the result is still 1.

Example 4-4. Order of precedence

2 + 4 − 5  == 1;
4 − 5 + 2 == 1;

4 * 5 / 2 == 10;
5 / 2 * 4 == 10;

2 + 4 − 5  == 1;
4 − 5 + 2 == 1;

4 * 5 / 2 == 10;
5 / 2 * 4 == 10;

When using expressions that contain operators of different precedence levels, the order can change the value of the expression. You can use parentheses, ( and ), to override the precedence levels or just to make the expression easier to read. Example 4-5 shows how to change the default precedence.

Example 4-5. The multiplication is done last because of the override

echo 2 * 3 + 4 + 1;
11
echo 2 * (3 + 4 + 1);
16

PHP has several levels of precedence, enough so that it's difficult to keep track of them without checking a reference. Table 4-2 is a list of operators in PHP sorted by order of precedence from highest to lowest. Operators with the same level number are all of the same precedence.

Tip

The Association column lists operators that are right to left instead of left to right. We'll discuss associativity next.

Table 4-2. List of PHP operators

Operator

Description

Operands

Association

Level

NEW

Create new object

Constructor call

Right to left

1

.

Property access (dot notation)

Objects

 

2

[ ]

Array index

Array, integer, or string

 

2

()

Function call

Function or argument

 

2

!

Logical NOT

Unary

Right to left

3

~

Bitwise NOT

Unary

Right to left

3

++, --

Increment and decrement operators

1value

Right to left

3

+, -

Unary plus, negation

Number

Right to left

3

(int)

Cast operators

Unary

Right to left

3

(double)

Cast operators

Unary

Right to left

3

(string)

Cast operators

Unary

Right to left

3

(array)

Cast operators

Unary

Right to left

3

(object)

Cast operators

Unary

Right to left

3

@

Inhibit errors

Unary

Right to left

3

*, /, %

Multiplication, division

Numbers

 

4

+, -

Addition, subtraction

Numbers

 

5

.

Concatenation

Strings

 

5

<<, >>

Bitwise shift left, bitwise shift right

Binary

 

6

<, <=, >, >=

Comparison operators

Numbers, strings

 

7

==, !=

Equality, inequality

Any

 

8

===, !==

Identity, non-identity

Any

 

8

&

Bitwise AND

Binary

 

9

^

Bitwise NOR

Binary

 

10

|

Bitwise OR

Binary

 

11

&&

Logical AND

Boolean

 

12

||

Logical OR

Boolean

 

13

? :

Conditional

Boolean

Right to left

14

=

Assignment

1value=any

Right to left

15

AND

Logical AND

Boolean

 

16

OR

Logical OR

Boolean

 

17

XOR

Logical XOR

Boolean

 

18

Associativity

All operators process their operators in a certain direction. This direction is called associativity, and it depends on the type of operator. Most operators are processed from left to right, which is called left associativity. For example, in the expression 3 + 5 − 2, 3 and 5 are added together, and then 2 is subtracted from the addition, resulting in 8. Left associativity means that the expression is evaluated from left to right. Right associativity means the opposite.

Since it has right associativity, the assignment operator is one of the exceptions, since it has right associativity. The expression $a=$b=$c processes by $b being assigned the value of $c, and then $a being assigned the value of $b. This assigns the same value to all of the variables. If the assignment operator is right associative, the variables might not have the same value.

If you're thinking that this is incredibly complicated, don't worry. These rules are only enforced if you fail to be explicit about your instructions. Keep in mind that you should always use brackets in your expressions to make your actual meaning very clear. This helps both PHP and also other people who may need to read your code.

Relational Operators

In Chapter 3, we discussed assignment and math operators. Relational operators provide the ability to compare two operands and return either TRUE or FALSE regarding the comparison. An expression that returns only TRUE or FALSE is called a Boolean expression, which we discussed earlier in this chapter. These comparisons include tests for equality and less than or greater than. These comparison operators allow you to tell PHP when to do something based on a comparison being true so decisions can be made in your code.

Equality

The equality operator, a double equals sign (==), is used frequently. Using the single = in its place is a common logical error in programs, since it assigns values rather than tests equality.

If the two operands are equal, TRUE is returned; otherwise, FALSE is returned. If you're echoing your results, TRUE is printed as 1 in your browser. FALSE is 0, which won't display in your browser.

It's a simple construct but it also allows you to test for conditions. If the operands are of different types, PHP attempts to convert them before comparing.

For example, '1' == 1 is true. Also, $a == 1 is true if the variable $a is assigned to 1.

If you don't want the equals operator to automatically convert types, you can use the identity operator, a triple equals sign ===, which checks that the values and types are the same. For example, '1' === 1 is false because they're different types, since a string doesn't equal an integer.

Sometimes you might want to check to see whether two things are different. The inequality operator, an exclamation mark before the equals sign (!=), checks for the opposite of equality, which means not equal to.

'1' != 'A'    // true
'1' != '1'    // false

Comparison operators

You may need to check for more than just equality. Comparison operators test the relationship between two values. You may be familiar with these from high school math. They include less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=).

For example, 3<4 is TRUE, while 3<3 is FALSE but 3<=3 is TRUE.

Comparison operators are often used to check for something happening up until a set point. For example, a web store might offer free shipping if you purchase five or more items. So the code must compare the number of items to the number five before changing the shipping cost.

Logical operators

Logical operators work with the Boolean results of relational operators to build more complex logical expressions; there are four logical operators shown in Table 4-3.

Table 4-3. Logical operators

Logical operator

Meaning

AND

TRUE if both operands must be TRUE

OR

TRUE if at least one operand is TRUE

XOR

TRUE if only one operand is TRUE

NOT

TRUE if FALSE, FALSE if TRUE

To test whether both operands are true, use the AND operator, also represented as double ampersands (&&). TRUE is returned only if both operands are TRUE; otherwise, FALSE is returned. See Table 4-3 for more information.

To test whether one operand is TRUE, use the OR operator, which is also represented as double vertical bars (||). TRUE is returned only if either or both operands are TRUE.

Tip

Using the OR operator can create tricky program logic problems. If PHP finds that the first operand is TRUE, it won't evaluate the second operand. While this saves execution time, you need to be careful that the second operator doesn't contain code that needs to be executed for your program to work properly.

To test whether either operand is TRUE but not both, use XOR. XOR returns TRUE if one and only one operand is TRUE.

To negate a Boolean value, use the NOT operator represented as an exclamation point (!). It returns TRUE if the operand has a value of FALSE. It returns FALSE if the operand is TRUE.

Tip

If you accidentally use & instead of && or | instead of ||, you'll end up getting the wrong operator. They compare binary data bit by bit. PHP converts your operands into binary data and applies the binary operators.

Because they have different precedence levels, AND and OR have two representations. Table 4-4 displays logical statements and their results.

Table 4-4. Logical statements and their results

Example logical statement

Result

TRUE AND TRUE

TRUE

FALSE AND TRUE

FALSE

TRUE OR FALSE

TRUE

FALSE OR FALSE

FALSE

TRUE XOR TRUE

FALSE

!TRUE

FALSE

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required