Become a fan
Twitter
Home

PHP Operators

Author Joseph Stenhouse on December 9, 2010 | | |

PHP Operators broken down


Operators are the catalyst of operations. There are many types involved with PHP, those commonly used are:


Assignment Operators for assigning data to variables

Arithmetic Operators for performing basicmath functions

String Operators for joining two or more strings

Comparison Operators for comparing two pieces of data

Logical Operators for performing logical operations on Boolean values

In addition, PHP also provides:

Bitwise Operators for manipulating bits using boolean math

Error Control Operators for suppressing errors

Execution Operators for executing system commands

Incrementing/Decrementing Operators for incrementing and decrementing

numerical values

Type Operators for identifying Objects


With little expception, most operations in PHP are binary. This means that they require two operands, normally separated by an operator. All binary operations use an infix notation, in which the operator sits in between its operands (for example, 2+2).


Arithmetic Operators

Arithmetic operators allow you to perform basic mathematical operations:

Addition $a = 1 + 3.5;

Subtraction $a = 4 - 2;

Multiplication $a = 8 * 3;

Division $a = 15 / 5;

Modulus $a = 23 % 7;


Do remember that certain arithmetic operators (for example, the addition operator)

assume a different meaning when applied to arrays. You can find more information

on this subject in the Arrays chapter.

Incrementing/decrementing operators are a special category of operators that

make it possible to increment or decrement the value of an integer by one. They

are unary operators, because they only accept one operand (that is, the variable that

needs to be incremented or decremented), and are somewhat of an oddity, in that

their behaviour changes depending on whether they are appended or prepended to

their operand.

The position of the operator determines whether the adjustment it performs takes

place prior to, or after returning the value:

If the operator is placed after its operand, the interpreter will first return the

value of the latter (unchanged), and then either increment or decrement it by

one.

If the operator is placed before the operand, the interpreter will first increment

or decrement the value of the latter, and then return the newly-calculated

value.

Here are a few examples:

$a = 1;

// Assign the integer 1 to $a

echo $a++;

// Outputs 1, $a is now equal to 2

echo ++$a;

// Outputs 3, $a is now equal to 3

echo --$a;

// Outputs 2, $a is now equal to 2

echo $a--;

// Outputs 2, $a is now equal to 1

*The excessive use of this operator can make your code hard to understand—even the

best programmers have been tripped up at least a fewtimes by a misunderstood increment

or decrement operation. Therefore, you should limit your use of these operators

with caution.

It’s important to note that the operand in an increment or decrement operation

has to be a variable—using an expression or a hard-coded scalar value will simply

cause the parser to throw an error. Also, the variable being incremented or decremented

will be converted to the appropriate numeric data type—thus, the following

code will return 1, because the string Test is first converted to the integer number 0,

and then incremented:

$a = ’Test’;

echo ++$a;


The String Concatenation Operator

Unlike many other languages, PHP has a special operation that can be used to

glue—or, more properly, concatenate—two strings together:

$string = "foo" . "bar";

// $string now contains the value ’foobar’

$string2 = "baz";

// $string2 now contains the value ’baz’

$string .= $string2;

// After concatenating the two variables, we end up with ’foobarbaz’

echo $string;

// Displays ’foobarbaz’

It is important to remember that this is not just the proper way to concatenate two

strings using an operation—it is the only way. Using the addition operator will result

in the two strings being first converted to numeric values, and then added together

(thus also yielding a numeric value).


Bitwise Operators

Bitwise operators allow you to manipulate bits of data. All these operators are designed

to work only on integer numbers—therefore, the interpreter will attempt to

convert their operands to integers before executing them.

The simplest bitwise operator is binary not, which negates all the bits of an integer

number:

$x = 0;

echo ~$x; // will output -1

A group of binary bitwise operators is used to perform basic bit manipulation by

combining the bits of its two operands in various ways:

& Bitwise AND. The result of the operation will be a value whose bits are

set if they are set in both operands, and unset otherwise.

| Bitwise OR. The result of the operation will be a value whose bits are

set if they are set in either operand (or both), and unset otherwise.

ˆ Bitwise XOR (exclusive OR). The result of the operation will be a value

whose bits are set if they are set in either operand, and unset

otherwise.

These operations are all quite straightforward—with the possible exception of the

exclusive OR, which may look odd at first sight. In reality, its functionality is quite

simple: if either the left-hand or right-hand bit is set, the operand behaves in exactly

the same as the bitwise OR. If both bits are either set or unset, the resulting bit is

simply inverted.

A third set of operators is used to shift bits left or right:

<< Bitwise left shift. This operation shifts the left-hand operand’s bits

to the left by a number of positions equal to the right operand,

inserting unset bits in the shifted positions.

>> Bitwise right shift. This operation shifts the left-hand operand’s bits

to the right by a number of positions equal to the right operand,

inserting unset bits in the shifted positions.

It’s interesting to note that these last two operations provide an easy (and very fast)

way ofmultiplying integers by a power of two. For example:

$x = 1;

echo $x << 1; // Outputs 2

echo $x << 2; // Outputs 4

$x = 8;

echo $x >> 1; // Outputs 4

echo $x >> 2; // Outputs 2

You must, however, be aware of the fact that, even though these operations can approximate

a multiplication or a division by a power of two, they are not exactly the

same thing—in particular, there are overflow and underflow scenarios that can yield

unexpected results. For example, on a 32-bit machine, the following will happen:

$x = 1;

echo $x << 32;

echo $x * pow (2, 32);

The second line of this example actually outputs zero—because all the bits have been

shifted out of the integer value. On the other hand, the second example (which calls

the pow() function to elevate 2 to the power of 32) will return the correct value of

4,294,967,296—which, incidentally, will now be a float because such a number cannot

be represented using a signed 32-bit integer.


Assignment Operators

Given the creativity that we have shown in the naming conventions to this point,

you’ll probably be very surprised to hear that assignment operators make it possible

to assign a value to a variable. The simplest assignment operator is a single equals

sign, which we have already seen in previous examples:

$variable = ’value’;

// $variable now contains the string ’value’

In addition, it is possible to combine just about every other type of binary arithmetic

and bitwise operator with the = sign to simultaneously perform an operation on a

variable and reassign the resulting value to itself:

$variable = 1;

// $variable now contains the integer value 1

$variable += 3;

/*

$variable now contains the integer 4

*/

In this example, we pair the addition operator (the plus sign) with the equals sign to

add the existing value of $variable to the right operand, the integer 3. This technique

can be used with all binary arithmetic and bitwise operators.


Referencing Variables

By default, assignment operators work by value—that is, they copy the value of an

expression on to another. If the right-hand operand happens to be a variable, only

its value is copied, so that any subsequent change to the left-hand operator is not

reflected in the right-hand one. For example:

$a = 10;

$b = $a;

$b = 20;

echo $a; // Outputs 10

Naturally, you expect this to be the case, but there are circumstances in which you

may want an assignment to take place by reference, so that the left-hand operand

becomes “connected” with the right-hand one:

$a = 10;

$b = &$a; // by reference

$b = 20;

echo $a; // Outputs 20

*The assignment operator works by value for all data types, except objects, which are

always passed by reference, regardless of whether the & operator is used or not.

The use of by-reference variables is a sometimes-useful, but always very risky technique,

because PHP variables tend to stay in scope for a long time, even within a

single function. Additionally, unlike what happens in many other languages, byreference

activity is often slower than its by-value counterpart, because PHP uses

a clever “deferred-copy” mechanism that actually optimizes by-value assignments.


Comparison Operators

Comparison operations are binary operations that establish a relationship of equivalence

between two values. They can either establish whether two values are equal

(or not equal) to each other, and whether one is greater (or smaller) than the other.

The result of a comparison operation is always a Boolean value.

There are four equivalence operations:

== Equivalence. Evaluates to true if the two operands are equivalent,

meaning that they can be converted to a common data type in

which they have the same value but are not necessarily of the same

type.

=== Identity. Evaluates to true only if the operands are of the same data

type and have the same value.

!= Not-equivalent operator. Evaluates to true if the two operands are

not equivalent, without regards to their data type.

!== Not-identical operator. Evaluates to true if the two operands are

not of the same data type or do not have the same value.

As you can imagine, it’s easy to confuse the assignment operator = for the comparison

operator ==—and this is, in fact, one of the most common programming

mistakes. A partial solution to this problem consists of reversing the order of your

operands when comparing a variable to an immediate value. For example, instead

of writing:

echo $a == 10;

You could write:

echo 10 == $a;

These two operations are completely identical—but, because the left-hand operator

of an assignment must be a variable, if you had forgotten one of the equal signs, the

parser would have thrown an error, thus alerting you to your mistake.

A different set of operators establishes a relationship of inequality between two

operands—that is, whether one of the two is greater than the other:

< and <= Evaluates to true if the left operand is less than, or less than or

equal to the right operand.

> and >= Evaluates to true if the left operand is greater than or greater

than or equal to the right operand.

Clearly, the concept of relationship changes depending on the types of the values

being examined. While the process is clear for numbers, things change a bit for other

data types; for example, strings are compared by examining the binary value of each

byte in sequence until two different values are found; the result of a comparison

operation is then determined by the numeric value of those two bytes. For example:

$left = "ABC";

$right = "ABD";

echo (int) ($left > $right);

The code above echoes 0 (that is, false), because the letter D in $right is higher

than the corresponding letter C in $left. While you may think that this comparison

method is roughly equivalent to alphabetical comparison, this is almost never

the case when applied to real-world examples. Consider, for example, the following:

$left = ’apple’;

$right = ’Apple’;

echo (int) $left > $right;

This example outputs 1 (true), because the ASCII value of the character a (97) is

higher than that of the character A (65). Clearly, this approach won’t work well in

the context of text comparison, and a different set of functions is required—this is

explained in the Strings chapter.

*The use of comparison operators with arrays also introduces a different set of rules.

These are explained in the Arrays chapter.

Now, just a look at an example of a COMPARISON OPERATOR at work in a basic operation.

First, let's write our Select Query and fire it:


$query = "SELECT * FROM my_table WHERE magic_number=6 ORDER BY id DESC";
$result = mysql_query($query);

So now, for all of the rows that meet the conditional value of 6 from the field magic_number, we will write a WHILE LOOP to grab specific data from those rows where later it will be displayed on an HTML page in Descending order (DESC) according to their id.


Let's check to see if there is at least 1 result and if so, run the loop:

if(mysql_num_rows($result) > 0){ // here is where we used our operator.

while($rows=mysql_fetch_array($result)){
echo “The type is “ . $rows['type'] . '</br>';

}

}else{

echo “No rows were found”;

}


However many rows that are listed from the loop in the field “type” depends on how many times the value “6” was found in the field magic_number.


If there is only 1 row inserted in the table and within that row it meets the conditional value of magic_number=6, then that is all you will get, is one result. If you have 100 rows then the loop will scan all 100 rows until it can find no more that meet the condition we set. This was all stated in our original SELECT query.


Logical Operators

Logical operators are used to connect together Boolean values and obtain a third

Boolean value depending on the first two. There are four logical operators in PHP, of

which three are binary. The only unary operator is the Logical NOT, identified by a

single exclamation point that precedes its operand:

$a = false;

echo !$a; // outputs 1 (true)

It’s important to understand that all logical operators onlywork with Boolean values;

therefore, PHP will first convert any other value to a Boolean and then perform the

operation.

The three binary operators are:

&& / and The AND operator evaluates to true if both the left and right

operands evaluate to true. The most commonly-used formof

this operator is &&.

|| / or The OR operator evaluates to true if either the left or right

operands evaluate to true, with the || formbeing more

commonly used.

XOR The Exclusive OR operator evaluates to true if either the left

and right operands evaluates to true, but not both.

It’s important to understand that PHP employs a very simple shortcut strategy when

executing binary logical operations. For example, if the left-hand side operand of

an AND operation evaluates to false, then the operation returns false immediately

(since any other result would be impossible), without evaluating the right-hand side

operand at all.

In addition to improving performance, this approach is a lifesaver in many situations

where you actually don’t want the right-hand operand to be evaluated at all,

based on the first one.


Other Operators

In addition to all the operators we’ve seen this far, PHP also uses a few specialized

operators to simplify certain tasks. One of these is the error suppression operator

@; when prepended to an expression, this operator causes PHP to ignore almost all

error messages that occur while that expression is being evaluated:

$x = @mysql_connect();

The code above will prevent the call to mysql_connect() from outputting an error—

provided that the function uses PHP’s own functionality for reporting errors.

Sadly, some libraries output their errors directly, bypassing PHP and, therefore, make

it much harder to manage with the error-control operator.

The backtick operator makes it possible to execute a shell command and retrieve

its output. For example, the following will cause the output of the UNIX ls command

to be stored inside $a:

$a = ‘ls -l‘;

* Don’t confuse the backtick operator with regular quotes (and, conversely, don’t confuse

the latter with the former!)


Operator Precedence and Associativity

As we have all learned in school, not all operations have the same precedence. When

using an infix notation, the order in which operations are written in an expression

lends itself to a certain amount of ambiguitywhichmust, therefore, be resolved. This

can be done in one of two ways: using parentheses to indicate which operations

should be performed first, or by using a set of pre-defined precedence rules.

Even if we establish the precedence of each operation, however, we lack one important

tool: how do we decide in which order we execute operations that have the

same precedence? This is determined by an operation’s associativity, which can either

be left (operations are performed left-to-right), right (operations are performed

right-to-left) or none (for operations that cannot be associated).


The following table illustrates the precedence and associativity of each operation:


Associativity Operator


Associativity

Operator

left

[

non-associative

++ -

non-associative

! ˜ - (int) (float) (string) (array) (object) @

left

* / %

left

+ - .

left

<< >>

non-associative

< <= > >=

non-associative

== != === !==

left

&

left

ˆ

left

|

left

&&

left

||

left

? :

right

= += -= *= /= .= %= &= |= ˆ= <<= >>=

left

and

left

xor

left

or

left

,


*all information was either taken from involution media or Zend php 5 study book.

Was this article helpful?

Yes No

Category: PHP(Hypertext Preprocessor)

Last updated on December 9, 2010 with 740 views