Operators - PHP Programming: Learn PHP Programming - CRUSH IT IN ONE DAY. Learn It Fast. Learn It Once. Get Coding Today, First Edition(2015)

PHP Programming: Learn PHP Programming - CRUSH IT IN ONE DAY. Learn It Fast. Learn It Once. Get Coding Today, First Edition (2015)

Chapter 4. Operators

Something which takes one or more values and gives out another value is called an operator. The operator's precedence specifies how two different expressions are tightly bound. For example 1+5*3 equals to 16 and not 18. This is because the addition operator has a lesser precedence when compared to the multiplication operator. If necessary, parenthesis can be used to force precedence. For example, (1+5)*3, gives us 18.

Operator Precedence Table

Given below is the table that lists all the operators in their order of precedence from top to bottom. In the case of operators which are on the same line, precedence is equal. In such cases grouping is decided by case associativity.

Associativity

Operators

Additional Information

non-associative

clone new

clone and new

left

[

array()

right

**

arithmetic

right

++ -- ~ (int) (float) (string) (array) (object) (bool) @

types and increment/decrement

non-associative

instanceof

types

right

!

logical

left

* / %

arithmetic

left

+ - .

arithmetic and string

left

<< >>

bitwise

non-associative

< <= > >=

comparison

non-associative

== != === !== <>

comparison

left

&

bitwise and references

left

^

bitwise

left

|

bitwise

left

&&

logical

left

||

logical

left

? :

ternary

right

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

assignment

left

and

logical

left

xor

logical

left

or

logical

left

,

many uses

Here is an example programme which explains us associativity and undefined order of evaluation.

Example 1: Associativity

<?php

$a = 3 * 3 % 5; // (3 * 3) % 5 = 4

$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;

$b = 2;

$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5

?>

Associativity and operator precedence only determine how grouping of expressions are done but they do not determine the order of evaluation.

Example 2: Undefined Order of Evaluation

<?php

$a = 1;

echo $a + $a++; // may print either 2 or 3

$i = 1;

$array[$i] = $i++; //may set either index 1 or 2

?>

PHP uses different kinds of operators. Some of them are

Arithmetic Operators

These are the basic operators which we have learned in school. Here there is a table given below to explain the arithmetic operators.

Example

Name

Result

-$a

Negation

Opposite of $a.

$a + $b

Addition

Sum of $a and $b.

$a - $b

Subtraction

Difference of $a and $b.

$a * $b

Multiplication

Product of $a and $b.

$a / $b

Division

Quotient of $a and $b.

$a % $b

Modulus

Remainder of $a divided by $b.

$a ** $b

Exponentiation

Result of raising $a to the $b'th power.

When the division operator is used, it returns of float value unless both the integers are perfectly divisible, in this case it returns an integer value.

`Before processing the operandi of modulus will be converted into integers.

Here is an example

<?php

echo (5 % 3)."\n"; // prints 2

echo (5 % -3)."\n"; // prints 2

echo (-5 % 3)."\n"; // prints -2

echo (-5 % -3)."\n"; // prints -2

?>

Assignment Operators

"=" is the basic assignment operator. Don't mistake it to be "equal to". Here in PHP it means the left operand will get the right operand's expression value.

The value assigned will be the value of an assignment expression.

Example:

<?php

$a = ($b = 4) + 5;

?>

Here, $a is equal to 9 now, and $b has been set to 4.

Assigning a value to our named key in Arrays is performed by "=>". This operator's precedence is the same as the other given assignment operators.

There are also a set of combined operators in addition to the basic operators, for all array Union, string and basic arithmetic operators. Here is an example.

<?php

$a = 3;

$a += 5; //sets $a to 8, as if we had said: $a = $a + 5;

$b = "Hello ";

$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

Assignment by Reference:

Using the "$var=&$othervar;" syntax, assignment by reference is supported. Which is nothing but both the variables will end up pointing to the same data but nothing will be copied anywhere.

Here is an example

<?php

$a = 3;

$b = &$a; // $b is a reference to $a

print "$a\n"; // prints 3

print "$b\n"; // prints 3

$a = 4; // change $a

print "$a\n"; // prints 4

print "$b\n"; // prints 4 as well, since $b is a reference to $a, which has

// been changed

?>

Bitwise operators

Manipulation and evaluation of specific bits which are within an integer are allowed by the Bitwise operators. Here is a table of the Bitwise operators with examples.

Example

Name

Result

$a & $b

And

Bits that are set in both $a and $b are set.

$a | $b

Or (inclusive or)

Bits that are set in either $a or $b are set.

$a ^ $b

Xor (exclusive or)

Bits that are set in $a or $b but not both are set.

~ $a

Not

Bits that are set in $a are not set, and vice versa.

$a << $b

Shift left

Shift the bits of $a $b steps to the left (each step means “multiply by two")

$a >> $b

Shift right

Shift the bits of $a $b steps to the right (each step means "divide by two")

Comparison Operators

Using the comparison operators, two values can be compared. A table is given below with the comparison operators with examples.

Example

Name

Result

$a == $b

Equal

TRUE if $a is equal to $b after type juggling.

$a === $b

Identical

TRUE if $a is equal to $b, and they are of the same type.

$a != $b

Not equal

TRUE if $ais not equal to $b after type juggling.

$a <> $b

Not equal

TRUE if $a is not equal to $b after type juggling.

$a !== $b

Not identical

TRUE if $a is not equal to $b, or they are not of the same type.

$a < $b

Less than

TRUE if $a is strictly less than $b.

$a > $b

Greater than

TRUE if $a is strictly greater than $b.

$a <= $b

Less than or equal to

TRUE if $a is less than or equal to $b.

$a >= $b

Greater than or equal to

TRUE if $a is greater than or equal to $b.

$a <=> $b

Spaceship Operator

An integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b.

$a ?? $b ?? $c

Null Coalesce Operator

Returns the first operand from left to right that exists and not NULL. If nothing exists will return NULL.

When a number is compared with a string and when the comparisons sometimes involve numerical strings, then the string will be converted to numbers and numerical comparison will be performed. The same rules will also be applied to the switch statement. When the comparison is "===" or "!==", type comparison will not take place. This is because it involves both type and value comparisons.

Example:

<?php

var_dump(0 == "a"); // 0 == 0 -> true

var_dump("1" == "01"); // 1 == 1 -> true

var_dump("10" == "1e1"); // 10 == 10 -> true

var_dump(100 == "1e2"); // 100 == 100 -> true

switch ("a") {

case 0:

echo "0";

break;

case "a": // never reached because "a" is already matched with 0

echo "a";

break;

}

?>

According to the following table comparison for different types is done accordingly.

Type of Operand 1

Type of Operand 2

Result

null orstring

string

Convert NULL to "",numerical or lexical comparison

bool ornull

anything

Convert both sides to bool, FALSE<TRUE

object

object

Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its ownexplanation

string,resourceor number

string,resourceor number

Translate strings and resources to numbers, usual math

array

array

Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)

object

anything

object is always greater

array

anything

array is always greater

Here are some examples of various comparisons.

Example 1: Boolean/NULL comparison.

<?php

// Bool and null are compared as bool always

var_dump(1 == TRUE); //TRUE - same as (bool)1 == TRUE

var_dump(0 == FALSE); //TRUE - same as (bool)0 == FALSE

var_dump(100< TRUE); //FALSE - same as (bool)100<TRUE

var_dump(-10< FALSE);// FALSE - same as (bool)-10 < FALSE

var_dump(min(-100, -10, NULL, 10, 100)); // NULL - (bool)NULL < (bool)-100 is FALSE< TRUE

?>

Example 2: transcription of standard array comparison.

<?php

// Arrays are compared like this with standard comparison operators

function standard_array_compare($op1, $op2)

{

if (count($op1) < count($op2)) {

return -1; // $op1 < $op2

} elseif (count($op1) > count($op2)) {

return 1; // $op1 > $op2

}

foreach ($op1 as $key => $val) {

if (!array_key_exists($key, $op2)) {

return null; // uncomparable

} elseif ($val < $op2[$key]) {

return -1;

} elseif ($val > $op2[$key]) {

return 1;

}

}

return 0; // $op1 == $op2

}

?>

Ternary operator

Another of the conditional operators is the "?:" operator or the ternary operator. An example for the ternary operator is given below.

Example 3: ternary operator.

<?php

// Example usage for: Ternary Operator

$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement

if (empty($_POST['action'])) {

$action = 'default';

} else {

$action = $_POST['action'];

}

?>

One should remember that the ternary operator is just an expression. It evaluates the result of an expression but it will not evaluate the variable. If you're expecting a variable by reference this is an important point to remember. It is recommended not to use more than one ternary operator as it will result in the non-obvious behaviour of PHP. Here is an example for non-obvious ternary behaviour.

Example 4: Non-Obvious Ternary behaviour.

<?php

// on first glance, the following appears to output 'true'

echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'

// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above

echo ((true ? 'true' : false) ? 't' : 'f');

//here, you can see that the first expression is evaluated to 'true', which

// in turn evaluates to (bool)true, thus returning the true branch of the

// second ternary expression.

?>

Error Control operators

In PHP, there is one error control operator. That is the at sign(@). When it is used in front of an expression, any possible error message which might be generated by that particular expression will be ignored.

You can set a custom error and let function using set_error_handler(). Though this function will still be called, the custom error handler will call for error_reporting(). This will return 0 when the call which triggered the error has "@" in front of it.

You can save the error messages generated by different expressions using the track_errors feature. One should remember that this variable will be overwritten when it encounters a new error. The "@" operator can only be used with expressions. You can use "@" before functions, variables and also include it with constants, calls, and so forth but not before conditional structures, function or flash definitions. Here is an example where an intentional file with error was given and Error handler being used.

Example : error handling operator

<?php

/* Intentional file error */

$my_file = @file ('non_existent_file') or

die ("Failed opening file: error was '$php_errormsg'");

//this works for any expression, not just functions:

$value = @$cache[$key];

//will not issue a notice if the index $key doesn't exist.

?>

Execution operators

One execution operator is supported (``) by PHP. These are backticks and are not single quotes. The contents inside the backticks are executed as shell commands. This will return the output. Using the execution operator is identical to using shell_exec(). The backticks operator will be disabled when you use safe mode or when shell_exec() is disabled. We cannot use the backticks in the double-quoted strings. Here is an example program.

Example:

<?php

$output = `ls -al`;

echo "<pre>$output</pre>";

?>

Incrementing/Decrementing operators

Pre- and post- increment and decrement operations are supported by PHP. These operators only affect strings and numbers. Arrays, resources and objects cannot be affected. Here is a list of Increment and Decrement operators. As Booleans only have true and false, incriminating or decrementing operators will have no affect on them.

Example

Name

Effect

++$a

Pre-increment

Increments $a by one, then returns $a.

$a++

Post-increment

Returns $a, then increments $a by one.

--$a

Pre-decrement

Decrements $a by one, then returns $a.

$a--

Post-decrement

Returns $a, then decrements $a by one.

Hear a sample script is given as an example.

Example:

<?php

echo "<h3>Postincrement</h3>";

$a = 5;

echo "Should be 5: " . $a++ . "<br />\n";

echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";

$a = 5;

echo "Should be 6: " . ++$a . "<br />\n";

echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";

$a = 5;

echo "Should be 5: " . $a-- . "<br />\n";

echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";

$a = 5;

echo "Should be 4: " . --$a . "<br />\n";

echo "Should be 4: " . $a . "<br />\n";

?>

When dealing with arithmetic operations on characters, PHP follows Perl's convection. This is explained with the example given below.

Example: arithmetic operations on character variables.

<?php

echo '== Alphabets ==' . PHP_EOL;

$s = 'W';

for ($n=0; $n<6; $n++) {

echo ++$s . PHP_EOL;

}

//Digit characters behave differently

echo '== Digits ==' . PHP_EOL;

$d = 'A8';

for ($n=0; $n<6; $n++) {

echo ++$d . PHP_EOL;

}

$d = 'A08';

for ($n=0; $n<6; $n++) {

echo ++$d . PHP_EOL;

}

?>

And the output ofthe above codewill be

== Characters ==

X
Y
Z
AA
AB
AC

== Digits ==
A9
B0
B1
B2
B3
B4
A09
A10
A11
A12
A13
A14

And there are other operators like logical operators, string operators, type operators and Array operators.