Section 2.6. Operators


2.6. Operators

PHP contains three types of operators: unary operators, binary operators, and one ternary operator.

Binary operators are used on two operands:

 2 + 3 14 * 3.1415 $i  1 

These examples are also simple examples of expressions.

PHP can only perform binary operations on two operands that have the same type. However, if the two operands have different types, PHP automatically converts one of them to the other's type, according to the following rules (unless stated differently, such as in the concatenation operator).

Type of One of the Operands

Type of the Other Operand

Conversion Performed

Integer

Floating point

The integer operand is converted to a floating point number.

Integer

String

The string is converted to a number. If the converted string's type is real, the integer operand is converted to a real as well.

Real

String

The string is converted to a real.


Booleans, nulls, and resources behave like integers, and they convert in the following manner:

  • Boolean: False = 0, true = 1

  • Null = 0

  • Resource = The resource's # (id)

2.6.1. Binary Operators

2.6.1.1 Numeric Operators

All the binary operators (except for the concatenation operator) work only on numeric operands. If one or both of the operands are strings, Booleans, nulls, or resources, they are automatically converted to their numeric equivalents before the calculation is performed (according to the previous table).

Operator

Name

Value

+

Addition

The sum of the two operands.

-

Subtraction

The difference between the two operands.

*

Multiplication

The product of the two operands.

/

Division

The quotient of the two operands.

%

Modulus

Both operands are converted to integers. The result is the remainder of the division of the first operand by the second operand.


2.6.1.2 Concatenation Operator (.)

The concatenation operator concatenates two strings. This operator works only on strings; thus, any non-string operand is first converted to one.

The following example would print out "The year is 2000":

 $year = 2000; print "The year is " . $year; 

The integer $year is internally converted to the string "2000" before it is concatenated with the string's prefix, "The year is".

2.6.2. Assignment Operators

Assignment operators enable you to write a value to a variable. The first operand (the one on the left of the assignment operator or l value) must be a variable. The value of an assignment is the final value assigned to the variable; for example, the expression $var = 5 has the value 5 (and assigns 5 to $var).

In addition to the regular assignment operator =, several other assignment operators are composites of an operator followed by an equal sign. These composite operators apply the operator taking the variable on the left as the first operand and the value on the right (the r value) as the second operand, and assign the result of the operation to the variable on the left.

For example:

 $counter += 2;      // This is identical to $counter = $counter + 2; $offset *= $counter;// This is identical to $offset = $offset * $counter; 

The following list show the valid composite assignment operators:

 +=, -=, *=, /=, %=, ^=, .=,  &=, |=, <<=, >>= 

2.6.2.1 By-Reference Assignment Operator

PHP enables you to create variables as aliases for other variables. You can achieve this by using the by-reference assignment operator =&. After a variable aliases another variable, changes to either one of them affects the other.

For example:

 $name = "Judy"; $name_alias =& $name; $name_alias = "Jonathan"; print $name; 

The result of this example is

 Jonathan 

When returning a variable by-reference from a function (covered later in this book), you also need to use the assign by-reference operator to assign the returned variable to a variable:

 $retval =& func_that_returns_by_reference(); 

2.6.3. Comparison Operators

Comparison operators enable you to determine the relationship between two operands.

When both operands are strings, the comparison is performed lexicographically. The comparison results in a Boolean value.

For the following comparison operators, automatic type conversions are performed, if necessary.

Operator

Name

Value

==

Equal to

Checks for equality between two arguments performing type conversion when necessary:

1 == "1" results in true

1 == 1 results in true

!=

Not equal to

Inverse of ==.

>

Greater than

Checks if first operand is greater than second

<

Smaller than

Checks if first operand is smaller than second

>=

Greater than or equal to

Checks if first operand is greater or equal to second

<=

Smaller than or equal to

Checks if first operand is smaller or equal to second


For the following two operators, automatic type conversions are not performed and, therefore, both the types and the values are compared.

Operator

Name

Value

===

Identical to

Same as == but the types of the operands have to match.

No automatic type conversions are performed:

1 === "1" results in false.

1 === 1 results in true.

!==

Not identical to

The inverse of ===.


2.6.4. Logical Operators

Logical operators first convert their operands to boolean values and then perform the respective comparison.

Operator

Name

Value

&&, and

Logical AND

The result of the logical AND operation between the two operands

||, or

Logical OR

The result of the logical OR operation between the two operands

Xor

Logical XOR

The result of the logical XOR operation between the two operands


2.6.4.1 Short-Circuit Evaluation

When evaluating the logical and/or operators, you can often know the result without having to evaluate both operands. For example, when PHP evaluates 0 && 1, it can tell the result will be false by looking only at the left operand, and it won't continue to evaluate the right one. This might not seem useful right now, but later on, we'll see how we can use it to execute an operation only if a certain condition is met.

2.6.5. Bitwise Operators

Bitwise operators perform an operation on the bitwise representation of their arguments. Unless the arguments are strings, they are converted to their corresponding integer representation, and the operation is then performed. In case both arguments are strings, the operation is performed between corresponding character offsets of the two strings (each character is treated as an integer).

Operator

Name

Value

&

Bitwise AND

Unless both operands are strings, the integer value of the bitwise AND operation between the two operands.

If both operands are strings, a string in which each character is the result of a bitwise AND operation between the two corresponding characters in the operands. In case the two operand strings are different lengths, the result string is truncated to the length of the shorter operand.

|

Bitwise OR

Unless both operands are strings, the integer value of the bitwise OR operation between the two operands.

If both operands are strings, a string in which each character is the result of a bitwise OR operation between the two corresponding characters in the operands. In case the two operand strings are of different lengths, the result string has the length of the longer operand; the missing characters in the shorter operand are assumed to be zeros.

^

Bitwise XOR (exclusive or)

Unless both operands are strings, the integer value of the bitwise XOR operation between the two operands.

If both operands are strings, a string in which each character is the result of a bitwise XOR operation between the two corresponding characters in the operands. In case the two operand strings are of different lengths, the result string is truncated to the length of the shorter operand.


2.6.6. Unary Operators

Unary operators act on one operand.

2.6.7. Negation Operators

Negation operators appear before their operandfor example, !$var (! is the operator, $var is the operand).

Operator

Name

Value

!

Logical Negation

true if the operand evaluates to false.

False if the operand evaluates to true.

~

Bitwise Negation

In case of a numeric operand, the bitwise negation of its bitwise representation (floating-point values are first converted to integers).

In case of strings, a string of equal length, in which each character is the bitwise negation of its corresponding character in the original string.


2.6.8. Increment/Decrement Operators

Increment/decrement operators are unique in the sense that they operate only on variables and not on any value. The reason for this is that in addition to calculating the result value, the value of the variable itself changes as well.

Operator

Name

Effect on $var

Value of the Expression

$var++

Post-increment

$var is incremented by 1.

The previous value of $var.

++$var

Pre-increment

$var is incremented by 1.

The new value of $var (incremented by 1).

$var--

Post-decrement

$var is decremented by 1.

The previous value of $var.

--$var

Pre-decrement

$var is decremented by 1.

The new value of $var (decremented by 1).


As you can see from the previous table, there's a difference in the value of post- and pre-increment. However, in both cases, $var is incremented by 1. The only difference is in the value to which the increment expression evaluates.

Example 1:

[View full width]

$num1 = 5; $num2 = $num1++;// post-increment, $num2 is assigned $num1's original value print $num1; // this will print the value of $num1, which is now 6 print $num2; // this will print the value of $num2, which is the original value of $num1, thus, 5

Example 2:

[View full width]

$num1 = 5; $num2 = ++$num1;// pre-increment, $num2 is assigned $num1's incremented value print $num1; // this will print the value of $num1, which is now 6 print $num2; // this will print the value of $num2, which is the same as the value of $num1, thus, 6

The same rules apply to pre- and post-decrement.

2.6.8.1 Incrementing Strings

Strings (when not numeric) are incremented in a similar way to Perl. If the last letter is alphanumeric, it is incremented by 1. If it was 'z', 'Z', or '9', it is incremented to 'a', 'A', or '0' respectively, and the next alphanumeric is also incremented in the same way. If there is no next alphanumeric, one is added to the beginning of the string as 'a', 'A', and '1,' respectively. If this gives you a headache, just try and play around with it. You'll get the hang of it pretty quickly.

Note

Non-numeric strings cannot be decremented.


2.6.9. The Cast Operators

PHP provides a C-like way to force a type conversion of a value by using the cast operators. The operand appears on the right side of the cast operator, and its result is the converted type according to the following table.

Operator

Changes Type To

(int), (integer)

Integer

(float), (real), (double)

Floating point

(string)

String

(bool), (boolean)

Boolean

(array)

Array

(object)

Object


The casting operators change the type of a value and not the type of a variable. For example:

 $str = "5"; $num = (int) $str; 

This results in $num being assigned the integer value of $str (5), but $str remains of type string.

2.6.10. The Silence Operator

The operator @ silences error messages during the evaluation process of an expression. It is discussed in more detail in Chapter 7.

2.6.11. The One and Only Ternary Operator

One of the most elegant operators is the ?: (question mark) operator. Its format is

 truth_expr ? expr1 : expr2 

The operator evaluates truth_expr and checks whether it is true. If it is, the value of the expression evaluates to the value of expr1 (expr2 is not evaluated). If it is false, the value of the expression evaluates to the value of expr2 (expr1 is not evaluated).

For example, the following code snippet checks whether $a is set (using isset()) and displays a message accordingly:

 $a = 99; $message = isset($a) ? '$a is set' : '$a is not set'; print $message; 

This example prints the following:
 $a is set 



    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net