PHP variables are great for storing values in your script, but they’re not much use on their own. To manipulate variable values and get useful results, you need to use operators.
What are PHP operators?
PHP operators let you combine values together to produce new values. For example, to add two numbers together to produce a new value, you use the
+
(addition) operator. The following PHP code displays the number 5:<?php echo 2 + 3; ?>
The value or values that an operator works on are known as operands. In this tutorial you look at common PHP operators, and you also explore the concept of operator precedence.
Common PHP operators
There are many PHP operators, but this article concentrates on the ones you’re likely to use most often. These can be broken down into the following operator types:
Arithmetic | Carry out arithmetic operations such as addition and multiplication |
Assignment | Assign values to variables |
Comparison | Compare 2 values |
Bitwise Operators | Allow evaluation and manipulation of specific bits within an integer. |
Increment/decrement | Increase or decrease the value of a variable |
Logical | Perform Boolean logic |
String | Join strings together |
Error Control Operators | the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. |
Ternary Operator | A ternary operator can be used as a slightly faster, cleaner way to write simple if/else statements. |
The following sections explore each of these operator types.
ARITHMETIC OPERATORS
PHP features 5 arithmetic operators:
Symbol | Name | Example | Result |
+ | addition | echo 7 + 5 | 12 |
- | subtraction | echo 7 - 5 | 2 |
* | multiplication | echo 7 * 5 | 35 |
/ | division | echo 7 / 5 | 1.4 |
% | modulus | echo 7 % 5 | 2 |
The first four operators should be self-explanatory.
%
(modulus) is simply the remainder of dividing the two operands. In this case, 7 divided by 5 is 1 with a remainder of 2, so the result of the modulus operation is 2.ASSIGNMENT OPERATORS
The basic assignment operator is
=
(an equals sign). This is used to assign a value to a variable<?php $myVariable = 23; ?>
The value to assign doesn’t have to be a literal value — it can be any expression. In the following example,
$myVariable
takes on the value 12:<?php $firstNum = 7; $secondNum = 5; $myVariable = $firstNum + $secondNum; ?>
As with most PHP operators, the assignment operator doesn’t just carry out the operation — it also produces a resulting value, which in this case is the value that was assigned. This allows you to write code such as:
In this example,
$myVariable
is assigned the value 12 (the result of $firstNum + $secondNum
). This assignment operation also produces a result of 12, which is then assigned to $anotherVariable
. So both$myVariable
and $anotherVariable
end up storing the value 12. You can also combine many operators with the assignment operator — these are known as combined assignment operators. For example, say you wanted to add 3 to the value of $myVariable
. You could write:<?php $myVariable = $myVariable + 3; ?>
However, with a combined assignment operator, you can simply write:
<?php $myVariable += 3; ?>
COMPARISON OPERATORS
PHP’s comparison operators compare 2 values, producing a Boolean result oftrue
if the comparison succeeded, orfalse
if it failed. You often use comparison operators with statements such asif
andwhile
. PHP supports the following 8 comparison operators:
Symbol | Name | Usage | Result |
== | equal to | a == b | true if a equals b, otherwise false |
!= | not equal to | a != b | true if a does not equal b, otherwise false |
=== | identical to | a === b | true if a equals b and they are of the same type, otherwisefalse |
!== | not identical to | a !== b | true if a does not equal b or they are not of the same type, otherwise false |
< | less than | a < b | true if a is less than b, otherwise false |
> | greater than | a > b | true if a is greater than b, otherwise false |
<= | less than or equal to | a <= b | true if a is less than or equal to b, otherwise false |
>= | greater than or equal to | a >= b | true if a is greater than or equal to b, otherwise false |
PHP displays the value
true
as the number 1, and the value false
as an empty string. So the following lines of code each display 1 because the comparison operations evaluate to true
:<?php echo ( 7 == 7 ); echo ( 3 < 5 ); echo ( 6 === 6 ); ?>
The following lines of code each display nothing at all (an empty string) because the comparison operations evaluate to
false
:<?php echo ( 7 != 7 ); echo ( 3 > 5 ); echo ( 6 === "6" ); ?>
(The last comparison evaluates to
false
because 6 (an integer) and “6″ (a string) are not of the same type, even though their values are essentially equal.)
Bitwise Operator
The bitwise operators and binary math in general have always been a mystery to me. If not for studying for the zend certification I still would probably not care to learn them However here I am and I finally got down the mystery of bits and bytes. What this tutorial will cover: 1. What are bits and bytes and binary math? 2. PHP’s Bitwise Operators 3. A simple usecase for why you would want to use bitwise operators
What is Bits, Bytes, and Binary Math BINARY MATH INTRODUCTION
The bitwise operators utilize something called Binary Math. If you already know binary math, skip ahead. Binary math is a BASE 2 numbering system, where as our normal everyday numbering system is a BASE 10 system.
Think back to elementary school where we learned numbers this way… Think of the number 4768. That’s a normal everyday decimal number.
If you write that out full its 4 THOUSAND, 7 HUNDRED, 6 TENS, 8 ONES or (4 * 103) + (7 * 102) + (6 * 101) + (8 * 100) = 4768 The BASE 2 system has the same concept however it goes by 2′s instead of 10s. So you can only have a value of 0 or 1.
Lets look at a binary number
00101101 = (0 * 27) + (0 * 26) + (1 * 25) + (0 * 24) + (1 * 23) + (1 * 22) + (0 * 21) + (1 * 20) = 32 + 8 + 4 + 1 = 45
Wow thats alot of math. Lets break it down piece by piece starting with the first parentheses. (0 * 27) which means 0 TIMES 2 to the POWER of 7 or 0 * ( 2 * 2 * 2 * 2 * 2 * 2 * 2) which basically comes out to 0 * 128 which equals 0 (0 times anything is 0) so going down our binary number we can see it calculates like this:
0 – (0 * 128) = 0 0 – (0 * 64) = 0 1 – (1 * 32) = 32 0 – (0 * 16) = 0 1 – (1 * 8) = 8 1 – (1 * 4) = 4 0 – (0 * 2) = 0 1 – (1 * 1) = 1
so add those all up together 32 + 8 + 4 + 1 and you get 45 What is a bit? A bit is a representation of 1 or 0.
Basically OFF and ON. Why do computers use such simple math? Well computers process with electric current so if the current is over a certain level the computer considers that to mean ON or 1 and if it is under that level it is set to OFF or 0.
What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set.
We will look at why a byte’s maximum value is 255 in just a second. What does a byte look like?
1 Byte ( 8 bits ) | ||||||||||
Place Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
That is a representation of 1 Byte. The “Place Value” column represents the math we did doing 2 to the power of 7,6,5,4,3,2,1,0 So if all bits are set and the value = 255 my byte would look like this
1 Byte ( 8 bits ) | ||||||||||
Place Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | ||
1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | = | 255 |
How do we get 255? Lets take it right to left and add up all those values together
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255
What would the number 22 look like?
1 Byte ( 8 bits ) | ||||||||||
Place Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | ||
0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | = | 22 |
2 + 4 + 16 = 22
Let’s look at some other examples of decimal to binary, the ones on the end try for yourself.
43 = 00101011 4 = 00000100 230 = ? 65 = ? 31 = ?
PHP’S BITWISE OPERATORS
You can find complete detail on the PHP bitwise operators here:http://www.php.net/manual/en/language.operators.bitwise.phpWhat are going to cover? We’re going to cover the bitwise operators below and see how they work
Example | Name | Result |
$a & $b | And | Bits that are set in both $a and $b are set. |
$a | $b | Or | Bits that are set in either $a or $b are set. |
$a ^ $b | Xor | 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”) |
Lets use two variables to get started with the “And” operator &. The & or “And” operator takes two values and returns a decimal version of the binary values the left and right variable share.
So using our tables above we can see that the only bit these two share is in the 8 position so $a & $b = 8.
<?php $a =9; $b =10; echo $a & $b; ?>
This would output the number 36. Why?? Well lets see using our table example again
1 Byte ( 8 bits ) | ||||||||||
Place Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | ||
$a | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | = | 36 |
$b | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | = | 103 |
So you can see the only bits these two share together are the bits 32 and 4 which when added together return 36. This operator is saying “I want to know what bits you both have set in the same column”
Lets move on to the | also known as the “OR” operator.
<?php $a =9; $b =10; echo $a | $b; ?>
This would output the number 11. Why?? Well lets see using our table example
1 Byte ( 8 bits ) | ||||||||||
Place Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | ||
$a | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | = | 9 |
$b | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | = | 10 |
If you notice we have 3 bits set, in the 8, 2, and 1 column.. add those up 8+2+1 and you get 11. It is just saying “I want to know what bits either one of you guys have set”.
Moving on to the ^ operator also known as the “Xor” operator.
<?php $a =9; $b =10; echo $a ^ $b; ?>
This would output the number 3. Why?? Well lets see using our table example
1 Byte ( 8 bits ) | ||||||||||
Place Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | ||
$a | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | = | 9 |
$b | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | = | 10 |
The XOR operator wants to know “Tell me what bits you both have set but I dont want any bits you share” Notice we have 3 bits set but both $a and $b share the 8 bit, we dont want that one, we just want the 2 bit and the 1 bit that they each have set but don’t share. Soooo 2+1 = 3
OK, here is one that gets tricky the ~ operator also known as the “NOT” operator.
<?php $a =9; $b =10; echo $a & ~$b; ?>
This would output the number 1. Why?? Well lets see using our table example
1 Byte ( 8 bits ) | ||||||||||
Place Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | ||
$a | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | = | 9 |
$b | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | = | 10 |
The NOT operator wants to know what is set in $a but NOT set in $b because we marked $b with the ~operator in front of it.
So looking at our table we can see the only bit set in $a thats not in $b is 1. What happens if we do this…?
<?php $a =9; $b =10; echo ~$a & $b; ?>
We get the value 2, because we want the bits set in $b but NOT set in $a this time, so since they both share the 8 bit, 2 bit is the only one $b has that $a does not.
BIT SHIFTING TIME!!!
<?php $a =16; echo $a << 2; ?>This would output the number 64. Why?? Well lets see using our table example
1 Byte ( 8 bits ) Place Value 128 64 32 16 8 4 2 1 $a – BEFORE! 0 0 0 1 0 0 0 0 = 16 $a – AFTER! 0 1 0 0 0 0 0 0 = 64 How do we get 64? well bit shifting tells PHP to take the variable $a which in our case is 16 and shift if 2 bits which is basically like saying take 16 and multiply it by 2 twice. So 16 X 2 = 32 x 2 = 64So what useful things can you do with the bitwise operations?Here is a VERY simple and watered down user permissions system.This is great if you have many classes of permission for users for example… a user can…read articles write articles edit articles be an local Administrator be a global Administrator So you can setup your permission rules like this in your configuration file<?php $read = 1; $write = 2; $readwrite = 16; $local_admin = 32; $global_admin = 64; $jim = 96; $mike = 16; echo "Is Mike Allowed to edit? he has an access level of 16<BR>"; if($mike & 32) { echo 'YES MIKE CAN EDIT'; } else { echo 'NO HE CANNOT'; } echo "<BR><BR>Is Jim Allowed to edit? he has an access level of 96<BR>"; if($jim & 32) { echo 'YES JIM CAN EDIT'; } else { echo 'NO HE CANNOT'; } ?>When you run that code you’ll see Is Mike Allowed to edit? he has an access level of 16 NO HE CANNOT Is Jim Allowed to edit? he has an access level of 32 YES JIM CAN EDIT Using the AND operator we can clearly see if Mike has the 32 bit set that is required for this local admin operation, not only is Jim a local admin but he’s also a global admin with the 64 and 32 bit set giving him a 96 permission level. Imagine if you had 20 different levels of access in your application, being able to store all those in a single integer is VERY handy instead of having to do something like if(is_local_admin && is_global_admin && can_edit_articles && can_view_articles) etc…. that could get long, ugly and hard to manage. Thats about all I have time for at the moment, but I hope to add more useful things you can do with bitwise operators in the future.INCREMENT/DECREMENT OPERATORS
These two operators are very simple — they increase or decrease the value of a variable by 1:
Symbol Name Example Result ++
increment $x++
or++$x
Adds 1 to the variable $x
--
decrement $x--
or--$x
Subtracts 1 from the variable $x
The increment and decrement operators are handy when looping through a set of data, or when counting in general. If you place the operator after the variable name then the expression’s value is the value of the variable before it was incremented or decremented. For example, the following code displays the number 4, even though$x
‘s value is increased to 5:<?php $x = 4; echo $x++; ?>On the other hand, if you place the operator before the variable name then the expression evaluates to the value of the variable afterit was incremented or decremented. For example, this code displays the number 5:<?php $x = 4; echo ++$x; ?>LOGICAL OPERATORS
PHP’s logical operators combine values using Boolean logic. Each value to be combined is treated as either true or false — for example,1
,true
, a non-empty string, and a successful comparison are all considered true, while0
,false
, an empty string, and an unsuccessful comparison are all considered false. The true and/or false values are then combined to produce a final result of eithertrue
orfalse
. PHP supports 6 logical operators:
Symbol Name Example Result &&
and a &&
btrue
if a and b aretrue
, otherwisefalse
and
and a and
btrue
if a and b aretrue
, otherwisefalse
||
or a ||
btrue
if a or b aretrue
, otherwisefalse
or
or a or
btrue
if a or b aretrue
, otherwisefalse
xor
xor a xor
btrue
if a or b — but not both — aretrue
, otherwisefalse
!
not !
atrue
if a isfalse
;false
if a istrue
Note:and
andor
carry out the same operations as&&
and||
; however the former have lower precedencethan the latter. Usually you’ll want to use&&
and||
, rather thanand
oror
. PHP’s logical operators are often used with comparison operatorsto make more complex comparisons.STRING OPERATORS
The main string operator is the.
(dot) operator, which is used to join, or concatenate, two or more strings together. For example, the following code displays “Hello there!”:<?php echo "Hello " . "there!"; ?>As with many other operators, you can combine the.
operator with the=
operator to produce a combined assignment operator (.=
). The following code also displays “Hello there!”:<?php $a = "Hello"; $a .= " "; $a .= "there!"; echo $a; ?>Error Control Operators
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.<?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. ?>Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.Ternary Operators
The PHP ternary operator is a shorthand way of writing an if/else conditional statement. At first, it can be confusing to understand and may not be as easy to read as your standard if/else conditional statement. However, as you continue to use it you will realize that it is very useful when you want to save a few lines as well as tidy up your code. It is called the ternary operator because it takes three operands – a condition, a result for true, and a result for false. The condition is separated from the results by a ‘?’ question mark. The first result which returns if the condition evaluates to true is separated by a ‘:’ colon from the second result which returns if the condition evaluates to false. Your standard if/else conditional statement may look something like this:if (condition) { $variable = true; } else { $variable = false; } The same five lines of code above can be written in one line of code using the PHP ternary operator:$variable = (condition) ? true : false;A more real world example might look something like this:<?php // standard if/else conditional statement $compiled = true; if ($compiled) { $language = 'C'; } else { $language = 'PHP'; } // the same statement above using the ternary operator $language = ($compiled) ? 'C' : 'PHP'; ?>You can also use the ternary operator to echo strings:<?php // standard if/else conditional statement if (condition) { echo 'condition is true'; } else { echo 'condition is false'; } // the same statement above using the ternary operator echo (condition) ? 'condition is true' : 'condition is false'; ?>As you can see, the ternary operator can be very helpful for cleaning up your code. I wouldn’t recommend using it for complex conditional statements but for simple ones it is a great tool.
0 comments:
Post a Comment