In this part of the PHP programming tutorial, we will talk about operators.
An
We have several types of operators:
+ and - signs can be addition and subtraction operators as well as unary sign operators. It depends on the situation.
The following example shows arithmetic operations.
A typical example follows.
Notice that the relational operators are not limited to numbers. We can use them for other objects as well. Although they might not always be meaningful.
The one sign (=) operator is the assignment operator. It loads a value to a variable.
The two signs (==) operator is the loose equality operator. It is used to test if the values in question are equal. Note, that PHP interpreter does some implicit casting when this operator is used. This leads to some non intuitive results.
The three sign (===) operator is the strict comparison operator. It is called the identity operator. This operator returns true only if the values of the operands are equal and are of the same type.
The bitwise negation operator changes each 1 to 0 and 0 to 1.
The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.
Other compound operators are:
What is the outcome of the following expression? 28 or 40?
The following list shows common PHP operators ordered by precedence (highest precedence first):
Operators on the same line in the list have the same precedence.
Arithmetic, boolean, relational and bitwise operators are all left to right associated.
On the other hand, the assignment operator is right associated.
The compound assignment operators are right to left associated.
The reference ( & ) operator. It creates a reference to an object.
The backtick ( ` ) operator. It is used to execute commands. It is identical to the
In this part of the PHP tutorial, we covered the PHP operators.
An
operator
is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data.We have several types of operators:
- Arithmetic operators
- Boolean operators
- Relational operators
- Bitwise operators
operand
is one of the inputs (arguments) of an operator. Those operators that work with only one operand are called unary operators. Those who work with two operands are called binary operators. + and - signs can be addition and subtraction operators as well as unary sign operators. It depends on the situation.
php > print +2;The plus sign can be used to indicate that we have a positive number. But it is mostly not used. The minus sign changes the sign of a value.
2
php > print -2;
-2
php > print 2;
2
php > print 2+2;
4
php > print 2-2;
0
php > $a = 1;Multiplication and addition operators are examples of binary operators. They are used with two operands.
php > print -$a;
-1
php > print -(-$a);
1
php > print 3 * 3;
9
php > print 3 + 3;
6
The assignment operator
The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In PHP, a variable begins with a $ character. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.php > $x = 1;Here we assign a number to an $x variable.
php > print $x;
1
php > $x = $x + 1;The previous expression does not make sense in mathematics. But it is legal in programming. The expression means that we add 1 to the $x variable. The right side is equal to 2 and 2 is assigned to x.
php > print $x;
2
php > 3 = $x;This code example results in syntax error. We cannot assign a value to a literal.
Parse error: syntax error, unexpected '=' in php shell code on line 1
Arithmetic operators
The following is a table of arithmetic operators in PHP.Symbol | Name |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo |
<?phpAll these are known operators from mathematics.
$a = 10;
$b = 11;
$c = 12;
$add = $a + $b +$c;
$sub = $c - $a;
$mult = $a * $b;
$div = $c / 3;
echo $add, " " , $sub, " ";
echo $mult," ", $div, " ";
echo "\n";
?>
$ php arithmetic.php
33 2 110 4
php > print 9 % 4;The % operator is called the modulo operator. It finds the remainder of division of one number by another.
1
9 % 4
, 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1. Concatenating strings
We use the dot . operator to concatenate strings.php > print 'return' . 'of' . 'the' . 'king';The dot operator makes one string from four pieces of strings.
returnoftheking
php > print 3 . 'apples';We can concatenate strings with numbers with the dot operator. Internally, the number is converted to a string a the two strings are concatenated in the end.
3apples
php > print 'apples' * 3;Using other operators with strings does not make much sense. We get zero.
0
php > print 'apples' - 'oranges';
0
php > print 'apples' + 'oranges';
0
php > print (Integer) 'apple';This is because in a numerical context, a string is equal to zero.
0
Boolean operators
In PHP, we haveand
, or
and negation !
boolean operators. With boolean operators we perform logical operations. These are often used with if and while keywords. <?phpThis example shows the logical and operator. The logical and operator evaluates to True only if both operands are True.
$a = (True and True);
$b = (True and False);
$c = (False and True);
$d = (False and False);
var_dump($a, $b, $c, $d);
?>
$ php andop.phpThe logical or operator evaluates to True, if either of the operands is True.
bool(true)
bool(false)
bool(false)
bool(false)
<?phpIf one of the sides of the operator is True, the outcome of the operation is True.
$a = (True or True);
$b = (True or False);
$c = (False or True);
$d = (False or False);
var_dump($a, $b, $c, $d);
?>
$ php orop.phpThe negation operator
bool(true)
bool(true)
bool(true)
bool(false)
!
makes True False and False True. <?phpThe example shows the negation operator in action.
$a = ! False;
$b = ! True;
$c = ! (4<3);
var_dump($a, $b, $c);
?>
$ php negation.phpAnd, or operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of and evaluates to false, the overall value must be false; and when the first argument of or evaluates to true, the overall value must be true. (wikipedia)
bool(true)
bool(false)
bool(true)
A typical example follows.
<?phpThe first part of the expression evaluates to False. The second part of the expression is not evaluated. Otherwise, we would get a Division by zero error.
$x = 10;
$y = 0;
if ($y != 0 and x/y < 100) {
echo "a small value";
}
?>
Relational Operators
Relational operators are used to compare values. These operators always result in boolean value.Symbol | Meaning |
---|---|
< | strictly less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
== | equal to |
!= or <> | not equal to |
=== | identical |
!== | not identical |
php > var_dump(3 < 4);As we already mentioned, the relational operators return boolean values.
bool(true)
php > var_dump(3 == 4);
bool(false)
php > var_dump(4 >= 3);
bool(true)
Notice that the relational operators are not limited to numbers. We can use them for other objects as well. Although they might not always be meaningful.
php > var_dump("six" == "six");We can compare string objects too. We can use relational operators for different object types. In our case we compare a string with a number.
bool(true)
php > var_dump("a" > 6);
bool(false)
php > var_dump('a' < 'b');
bool(true)
php > var_dump('a' < 'b');What exactly happens here? Computers do not know characters or strings. For them, everything is just a number. Characters are special numbers stored in specific tables. Like ASCII.
<?phpInternally, the a and b characters are numbers. So when we compare two characters, we compare their stored numbers. The built-in
echo 'a' < 'b';
echo "\n";
echo 'a is:', ord('a');
echo "\n";
echo 'b is:', ord('b');
echo "\n";
?>
ord()
function returns the ASCII value of a single character. $ php compare.phpIn fact, we compare two numbers. 97 with 98.
1
a is:97
b is:98
php > print "ab" > "aa";Say we have a string with more characters. If the first characters are equal, we compare the next ones. In our case, the b character at the second position has a greater value than the a character. That is why "ab" string is greater than "aa" string. Comparing strings in such a way does not make much sense, of course. But it is technically possible.
1
Assignment, equality and identity
As you might notice, there are one sign operator (=), two signs operator (==) and three signs (===) operator. Now we will talk about the differences among these operators.The one sign (=) operator is the assignment operator. It loads a value to a variable.
php > $a = 6;In the example, we assign a value 6 to the $a variable. $a now contains number six. We can show the contents of the $a variable by using the
php > echo $a;
6
echo
command. The two signs (==) operator is the loose equality operator. It is used to test if the values in question are equal. Note, that PHP interpreter does some implicit casting when this operator is used. This leads to some non intuitive results.
php > var_dump(false == 0);For many programmers, beginners or programmers coming from other languages, these results might be surprising. If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
bool(true)
php > var_dump(false == array());
bool(true)
php > var_dump(true == 1);
bool(true)
php > var_dump(true == "string");
bool(true)
php > var_dump(117 == "000117");
bool(true)
The three sign (===) operator is the strict comparison operator. It is called the identity operator. This operator returns true only if the values of the operands are equal and are of the same type.
php > var_dump(false === 0);As we can see, the identity operator returns the opposite results. This operator is more intuitive and more safe to use.
bool(false)
php > var_dump(false === array());
bool(false)
php > var_dump(true === 1);
bool(false)
php > var_dump(true === "string");
bool(false)
php > var_dump(117 === "000117");
bool(false)
Bitwise operators
Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. We have binary logical operators and shift operators. Bitwise operators are seldom used in higher level languages like PHP.Symbol | Meaning |
---|---|
~ | bitwise negation |
^ | bitwise exclusive or |
& | bitwise and |
| | bitwise or |
<< | left shift |
>> | right shift |
php > print ~7;The operator reverts all bits of a number 7. One of the bits also determines, whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.
-8
php > print ~-8;
7
The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.
00110The first number is a binary notation of 6. The second is 3. The result is 2.
& 00011
= 00010
php > print 6 & 3;The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.
2
php > print 3 & 6;
2
00110The result is
| 00011
= 00111
00110
or decimal 7. php > print 6 | 3;The bitwise exclusive or operator performs bit-by-bit comparison between two nubmers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.
7
00110The result is
^ 00011
= 00101
00101
or decimal 5. php > print 6 ^ 3;Finally, we also have bitwise shift operators. The bitwise shift operators shift bits to the right or left.
5
number << n : multiply number 2 to the nth powerThese operators are also called arithmetic shift.
number >> n : divide number by 2 to the nth power
00110We shift each of the bits of number six to the right. It is equal to dividing the six by 2. The result is
>> 00001
= 00011
00011
or decimal 3. php > print 6 >> 1;
3
00110We shift each of the bits of number six to the left. It is equal to multiplying the number six by 2. The result is
<< 00001
= 01100
01100
or decimal 12. php > print 6 << 1;
12
Compound assignment operators
The compound assignment operators consist of two operators. They are shorthand operators.php > $i = 1;The += compound operator is one of these shorthand operators. They are less readable than the full expressions but experienced programmers often use them.
php > $i = $i + 1;
php > print $i;
2
php > $i += 1;
php > print $i;
3
Other compound operators are:
-= *= .= /= %= &= |= ^= >>= <<=
Operator precedence
The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.What is the outcome of the following expression? 28 or 40?
3 + 5 * 5Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.
(3 + 5) * 5To change the order of evaluation, we can use square brackets. Expressions inside square brackets are always evaluated first.
The following list shows common PHP operators ordered by precedence (highest precedence first):
Operator(s) | Description |
---|---|
++ -- | increment/decrement |
(int) (float) (string) (array) (object) (bool) | casting |
! | logical "not" |
* / % | arithmetic |
+ - . | arithmetic and string |
<< >> | bitwise |
< <= > >= <> | comparison |
== != === !== | comparison |
&& | logical "and" |
|| | logical "or" |
? : | ternary operator |
= += -= *= /= .= %= | assignment |
and | logical "and" |
xor | logical "xor" |
or | logical "or" |
, | comma operator |
<?phpIn this code example, we show some common expressions. The outcome of each expression is dependent on the precedence level.
print 3 + 5 * 5;
print "\n";
print (3 + 5) * 5;
print "\n";
var_dump(! True or True);
var_dump(! (True or True));
?>
var_dump(! True or True);In this case, the negation operator has a higher precedence. First, the first True value is negated to False, than the or operator combines False and True, which gives True in the end.
$ php precedence.phpThe relational operators have a higher precedence than logical operators.
28
40
bool(true)
bool(false)
<?phpThe and operator awaits two boolean values. If one of the operands would not be a boolean value, we would get a syntax error. In PHP, the relational operators are evaluated first. The logical operator then.
$a = 1;
$b = 2;
if ($a > 0 and $b > 0) {
echo "\$a and \$b are positive integers\n";
}
?>
$ php positive.php
$a and $b are positive integers
Associativity
Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity. The associativity of operators determines the order of evaluation of operators with the sameprecedence level.9 / 3 * 3What is the outcome of this expression? 9 or 1? The multiplication, deletion and the modulo operator are left to right associated. So the expression is evaluated this way:
(9 / 3) * 3
and the result is 9. Arithmetic, boolean, relational and bitwise operators are all left to right associated.
On the other hand, the assignment operator is right associated.
php > $a = $b = $c = $d = 0;If the association was left to right, the previous expression would not be possible.
php > echo $a, $b, $c, $d;
0000
The compound assignment operators are right to left associated.
php > $j = 0;You might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.
php > $j *= 3 + 1;
php > print $j;
0
Other operators
PHP has a silence ( @ ) operator. It is used to turn off error messaging. It is typically used with network or database connections. This operator should be used with caution, because it can lead to debugging issues.php > echo 3 / 0;In the first case, we receive a division by zero error message. In the second case, the @ operator turns off the error message.
Warning: Division by zero in php shell code on line 1
php > echo @ (3 / 0);
php >
The reference ( & ) operator. It creates a reference to an object.
php > $a = 12;In the above example, we pass a value to $a variable and pass a reference to the $a to the $b variable.
php > $b = &$a;
php > echo $b;
12
php > $b = 24;
php > echo $b;
24
php > echo $a;
24
php > $b = &$a;We create a new variable $b pointing to the $a variable. In other words, we create an alias for the $a variable.
php > $b = 24;Assigning a new value to $b will also affect the $a.
php > echo $b;
24
php > echo $a;
24
The backtick ( ` ) operator. It is used to execute commands. It is identical to the
shell_exec()
function call. php > $list = `ls -l`;We execute an ls command, which on Unix systems lists the contents of the current directory.
php > echo $list;
total 48
-rw-r--r-- 1 vronskij vronskij 127 2009-12-07 11:25 andop.php
-rw-r--r-- 1 vronskij vronskij 174 2009-12-07 10:48 arithmetic.php
-rw-r--r-- 1 vronskij vronskij 86 2010-01-16 15:11 atoperator.php
-rw-r--r-- 1 vronskij vronskij 106 2009-12-07 12:25 compare.php
...
In this part of the PHP tutorial, we covered the PHP operators.
0 comments:
Post a Comment