In the previous chapter, you learned about variables. You learned what a variable was, how to use it, and how to assign a value to it. If you noticed carefully, you’d have seen that I used the equals symbol (=) when assigning a value to a variable. This symbol, and many others, are called operators. Like other elements in these first few chapters of the tutorials, they are essential to building a PHP script, so learning what operators are and how they work will help you greatly when you start coding.
What are operators?
By simple definition, an operator is a symbol that performs some basic function in your script. Examples of these functions are assignment, like the equals sign that I just mentioned earlier, and calculation, like the +, -, *, and / symbols that you used while doing math in school.
Operators in PHP can be grouped into four groups based on their function. Here is a list of all operators in PHP:
Arithmetic Operators
Also known as mathematical operators, these guys perform basic mathematical calculations. You’ll be very familliar with most if not all of them.
| Symbol | Name | Description |
|---|---|---|
| + | Addition | Adds two variables or values together, and returns the new total. |
| - | Subtraction | Subtracts a first value or variable from the second, and returns the remainder. |
| * | Multiplication | Multiplies the first value or variable by the second, and returns the new amount. |
| / | Division | Divides the first value or variable by the second, and returns the new amount. |
| % | Modulus | Divides the first value or variable by the second, and returns the undividable remainder. |
| ++ | Increment | Increases a variable’s value by 1. |
| – | Decrement | Decreases a variable’s value by 1. |
As you can see, you’ve already seen most of these in basic math. The only ones that tend to trip beginner programmers up are the modulus, increment, and decrement operators. Before I go into explaining those three, allow me to provide some examples of the first four operators.
<?php $value = 3 + 5; //$value is now 8. $value = 7 - 3; //$value is now 4. $value = 24*4; //$value is...err...carry the 1...96! Yes, $value is now 96. $value = 6/4; //$value is now 1.5. ?>
As you can see, I’ve put spaces in between some of the operators, and not put spaces in the others. It doesn’t matter either way, and it’s a matter of personal preference. I find that not putting spaces in my operators helps me read them better, but feel free to use whatever works for you.
Now for the remaining three. The modulus operator (%) is probably the toughest among the three, and even then it’s a piece of cake. Let’s say you divide 10 by 3. You’d end up with 3.33333333. If you were to see that in fractions, it would look something like this: 3 1/3. A modulus operator basically will give you that value of 1 when you use it. Let’s try that in code with a few examples:
<?php $value = 5%2; //$value is now 1. $value = 10%6; //$value is now 4. $value = 10%2; //Since 10 can be divided completely by 2 with no remainder, $value is now 0. $value = 144%11; //$value is now 1. $value = 0%4; //In this case, $value is, of course, 0. ?>
A good example of when modulus would come in handy is when you’re doing pages for a blog. Using a modulus will tell you if you have just enough posts to fill give you full pages, or if there is some leftover posts that need an extra page.
Now, we’ll go to the increment and decrement operators. What they basically do is increase or decrease the value of a variable by 1. This may seem to you as being very specific, and not very helpful to general coding, but you’ll be surprised at how many functions rely on this tiny change in value.
<?php $value = 5; $value++; //$value is now 6. ++$value; // $value is now 7. $value = 11; $value--; //$value is now 10. --$value; //$value is now 9. ?>
The way you use the increment and decrement operators differ slightly from the previous five mathematical operators, and it’s vital that you understand this. First, you’ll notice that in the examples above, I didn’t use an assignment operator. This is because I’m not assigning a value to a new variable, I’m just increasing or decreasing the value of the current one. Second, notice how I can use the operators either before or after the variable? This is unique to increment and decrement operators, but here’s the thing: while they may look similiar from the outset, they actually vary slightly, and can change the value that you get in return. Take a look at these examples:
<?php $number = 6; $value = $number++; $number = 6; $value = ++$number; ?>
The difference only becomes apparent when you use an assignment operator with it, to assign the new value to a second variable. In the first example, my $number variable has a value of 6. I then assign the value of 6 to the $value variable, and then increase the value of $number by 1, making it 7. So at the end of the these two lines, the value is $value is 7, while the value of $number is 6.
In the second example, I again start with a variable $number that has a value of 6. Then, in the second line, because the increment operator comes before the $value variable, the increment happens before the assignment. This means that the value of $number is increased by 1, making it 7, and then it is assigned to $value. So at the end of these two lines, the value of $value and $number are both 7.
Assignment Operators
Assignment operators are, as the name suggests, operators that allow you to assign a value to a variable. Now, you may be thinking, what other way of assigning could there possibly be other than the equals sign (=)? And you’d be right to think so: there actually isn’t. However, PHP provides some assignment operators that have some arithmetic operators mixed in, to basically act as shortcuts. Here are the available operators:
| Symbol | Name | Description |
|---|---|---|
| = | Assign | Assigns a value to a variable |
| += | Add and Assign | Adds a value to a variable’s existing value, and updates the variable with the new value. |
| -= | Subtract and Assign | Subtracts a value from a variable’s existing value, and updates the variable with the new value. |
| *= | Multiply and Assign | Multiplies a variable’s existing value by a value, and updates the variable with the new value. |
| /= | Divide and Assign | Divides a variable’s existing value by a value, and updates the variable with the new value. |
| %= | Modulus and Assign | Divides a variable’s existing value by a value, and updates the variable with the undividable remainder. |
| .= | Concatenate and Assign | Joins a value to a variable’s existing value, and updates the variable with the new string. |
The first one is a no-brainer, so I’ll skip on ahead and talk about the next five, from Add and Assign to Modulus and Assign. For each one of them, they’re basically a shortcut for the longer arithmetic operators. Here’s an example:
<?php $value+=6; $value=$value+6; ?>
These two strings mean the same thing, and will give you the same result. A few more examples:
<?php $value = 10; $value-= 2; //$value is now 8. $value = 11; $value*= 2; //$value is now 22. $value = 14; $value/= 7; //$value is now 2. $value = 100; $value%= 40; //$value is now 20. ?>
Now for the last one. I know that some of you looking at the table above would have been going “Concata-what?”. Before I go into what the Concatenate and Assign operator does, allow me to explain the concatenate operator. To concatenate is to join two or more elements together. For example, if I were to concatenate the string “Hello” with the string “world”, I’d get the string “Helloworld” in return. Note that unlike the arithmetic operators that you saw previously, the Concatenate operator is meant to be used on strings. If your variables hold intergers and you concatenate them, PHP will convert them to strings first. To better explain the concept, here are some examples:
<?php $string = "Hello"."world"; //$string is now "Helloworld" $number1 = 6; $number2 = 14; $value = $number1.$number2; //$value is now "614", NOT 20 $value = $number2.$number1; //$value is now "146", NOT 20 $value = $number1.$string.$number2; //$value is now "6Helloworld14". Yikes. ?>
When using concatenation in your codes, it’s vital to remember this string-interger difference. If you put interger values into variables and then concatenate those variables, PHP will convert them to strings first, as seen in the example above. However, if you put the values in directly, you’ll see why PHP doesn’t concatenate the values:
<?php $number1 = 6.14; //$number1 has the value of 6.14 $number += 2; //$number1 is now 8.14 ?>
If intergers are used, PHP sees the period mark (.) as a decimal point indicator, instead of a concatenation operator, which makes sense. If you want to concatenate two intergers together, either convert them to strings by wrapping them with quote marks, or assigning them to variables and then concatenating those variables.
Now that you have a strong understanding of what the concatenate operator does, understanding what the Concatenate-and-Assign operator does should be a breeze. Here are some examples to help you anyway:
<?php $number = 54;//$number is now 54 $number .= 5;//$number is now '545' $number.='random';//$number is now '545random' ?>
Note that when using the Concatenate-and-Assign operator, the new string automatically comes after the old string. If you want it to come before instead, you’re going to have to do it the old-fashioned way.
<?php $value1 = 30; //$value1 is now 30 $value1 = "Level" . $value1; //$value1 is now "Level30" ?>
Comparison Operators
As the name suggests, comparison operators serve to compare two values or variables according to a certain rule, and return either true or false. You will be using these operators a lot in your conditional statements and loops, which I will cover in the next chapter, so it’s a good idea to get the hang of using these early on. Here are the various types of comparison operators:
| Symbol | Name | Description |
|---|---|---|
| == | Is Equal To | Returns true if the two values are equal, false otherwise. |
| != | Is Not Equal To | Returns true if the two values are not equal, false otherwise. |
| <> | Is Not Equal To | Returns true if the two values are not equal, false otherwise. |
| < | Is Lesser Than | Returns true if the value on the left is lesser than the value on the right, false otherwise. |
| > | Is Greater Than | Returns true if the value on the left is greater than the value on the right, false otherwise. |
| <= | Is Lesser Than or Equal To | Returns true if the value on the left is lesser than or equal to the value on the right, false otherwise. |
| >= | Is Greater Than or Equal To | Returns true if the value on the left is greater than or equal to the value on the right, false otherwise. |
| === | Is Exactly Equal To | Returns true if the two values are equal and of the same data type, false otherwise. |
| !== | Is Not Exactly Equal To | Returns false only if the two values are equal and of the same data type, true otherwise. |
First of all, I’m going to show you a sample conditional statement to show you how to use conditional operators.
<?php
if(1==2){
echo "The values are equal!";
};
?>
Don’t worry too much about the ‘if’ keyword and the curly brackets and all that for now. What we’re going to focus on is the statement between the parantheses (1==2). What we’re basically telling PHP to do is that if that statement is true, then perform the commands in the curly bracket (in this case, you’re telling PHP to echo the string “The values are equal!”). Now, of course, you know that 1 is not equal to 2, so PHP will not perform the following commands, and will skip until the end of the curly bracket. Now let’s look at a few other conditions for the Is Equal To operator:
<?php (2==3) //false (20==20) //true $number1 = 5; $number2 = 7; $number3 = 5; ($number1==$number2) //false ($number3==$number1) //true ?>
Got the idea? No? Don’t worry, you’ll get the hang of it in the next chapter. For now let’s move on to the other operators.
The next two (!= and <>) serve the exact same function. I have no idea why there are two of them, but for the most part, you’ll see the first version (!=) being used much more than the second. This is basically the opposite of the Is Equal To operator that we learned above. Here are some examples:
<?php (2!=3) //true (20!=20) //false $number1 = 5; $number2 = 7; $number3 = 5; ($number1!=$number2) //true ($number3!=$number1) //false ?>
The next two are Is Greater Than and Is Lesser Than. I’m going to cover them at once since if you understand one, you understand the other. Basically when you use the Is Greater Than operator, you are saying “Value on the left is greater than value on the right”, and likewise for Is Lesser Than. The important thing to remember here is which side are you looking at, and which side are you comparing it to. To further illustrate it, here are some examples:
<?php (20>35) //false (20<35) //true (20>10) //true (20<10) //false (1>1) //false (1<1) //false ?>
Note that the last two examples return false, because the values are equal. The operators Is Greater Than and Is Lesser Than will return false if the values on both sides are equal. What if we want it to return true if it was equal? That’s where the next two operators come in. The Is Greater Than Or Equal To and Is Lesser Than Or Equal To operators (wow, that was a mouthful) are similiar to their non-equal counterparts, except that if values on either side are equal, they will return true. To illustrate the difference, I’ll use the same values again for examples.
<?php (20>=35) //false (20<=35) //true (20>=10) //true (20<=10) //false (1>=1) //true (1<=1) //true ?>
Note that when using these two operators, the equals sign must come after the pointy arrow thingy (yeah, I know, but you get what I meant).
The last two are considered somewhat of an advanced pair of operators, and most basic PHP operator tutorials I’ve seen don’t include them, but nonetheless, they ARE operators, and you should learn about them now to get a solid understanding of them when you use them later on. The Is Exactly Equal To and Is Not Exactly Equal To operators are very similiar to Is Equal To and Is Not Equal To respectively, but have the added element of checking the TYPE of data. To make it clear, here are some examples:
<?php $value1 = "4"; //This is a string. $value2 = 4; //This is an interger. ($value1==$value2) //As you already know, this will return true, because the value is the same. ($value1!==$value2) //This will return false, because even though they are equal, they are not EXACTLY the same. A minor, but crucial difference. ?>
In the first comparison, the Is Equal To operator doesn’t check for datatype, so when one variable holds a string and one holds a value, it will still return true. In the second comparison, however, the Is Exactly Equal To operator checks for datatype, notices the difference, and proceeds to return as false. This difference also applies to their Not Equal counterparts, so the Is Not Exactly Equal To operator will only return false if both values are equal and of the same datatype.
Still with me? We’re almost done!
Logical Operators
Logical operators differ slightly from the other three groups in that they don’t really work alone, but with a comparison operator. That sounds rather confusing, but will become clear once I bury you in more examples. But before I do that, let’s take a look at the available logical operators:
| Symbol | Name | Description |
|---|---|---|
| && | AND | Returns true if statements on both sides are true |
| || | OR | Returns true if either statement is true |
| ! | NOT | Returns true if statement is false |
(Note: In case it’s not terribly clear, the symbol for the OR operator is actually Shift + the ‘’ key.)
The basic idea behind logical operators is simple: what if you want to modify a scenario based on different logical outcomes? Logical operators let you work with the various ‘true’ and ‘false’ statements that comparison operators will return, which allows you to tailor your code to exactly how you want to use it.
Let’s start with the AND operator (&&). Let’s say you want to check the weight of a bag. If it’s below 4kg, it’s too light, but if it’s over 8kg, it’s too heavy. So basically, an acceptable weight is above or equal to 4kg AND below or equal to 8kg. If you were doing comparison operators, you already know how to check for either one of these conditions. But that would mean you only define one end of the range (either the minimum or the maximum), while ignoring the other. For example:
<?php
//Define a minimum.
if($weight>=4){
$status = "okay";
};
?>
Any bag that weighs less than 4kg would be filtered out as not okay, which is what we want. However, even a 16kg bag would get passed as okay if we just used this. Not good, then. This is where the logical operator AND comes into play. Here’s how we do it:
<?php
//Define a minimum AND a maximum.
if($weight>=4 && $weight<=8){
$status = "okay";
};
?>
By using the AND operator (&&), I am telling PHP that the status is okay only if the statement on the left ($weight>=4) and the statement on the right ($weight<=8) BOTH return as true. If either one comes back as false, the condition fails, and PHP doesn’t run the command ($status=”okay”). You can stack as many AND operators as you like. Here’s an example:
<?php
if($bed=="made" && $clothes=="folded" && $homework=="done" && $dog=="fed" && $plates=="washed" && $car=="polished" && $fish_tank=="cleaned"){
$cookie_limit_for_today+=1;
};
?>
I know. I’m such a cruel parent.
Once you understand the AND operator, the OR operator becomes much simpler to learn. The difference is that instead of requiring BOTH statements to come true, the OR operator will return true if EITHER statement is true. Let’s say you’re shopping for shoes. Fun! You’re looking for either tan coloured shoes, or dark brown shoes. You already have all the other colours. Here’s how we’d write it:
<?php
if($shoe_color=="tan" || $shoe_color=="dark brown"){
$buy_shoes="yes";
};
?>
So basically if the salesperson shows you black, white, or funky orange shoes, you’re not going to buy it. Like the AND operator, you can extend it to as many as you want. I’m not going to give you examples of that, instead I’m going to move on to the NOT operator.
If the exclamation mark looks familliar, it’s because you’ve already used it. The Is Not Equal To and Is Not Exactly Equal To operators use the exclamation mark as the ‘not’ in their statement. Basically this operator flips the logic of whatever statement follows it. If that statement returns true, the NOT will return false, and vice versa. Let’s bring that shoe-buying example again. If the salesperson asks you if you’d like a bag for your shoes, chances are that you’ll say yes. But if you’re rather eco-friendly, you may think that you can just use whatever bag you have with you right now (from some other purchase), or may have even brought your own bag. So basically, if you have a bag, you’ll tell her no, but if you don’t have a bag, you tell her yes. This is how we’d write it:
<?php
if(!($have_bag=="yes")){
$take_bag="yes";
};
?>
Pay careful attention to the existence of that exclamation mark, now. Otherwise you’d be taking the bag if you already have a bag. Not very eco-friendly of you, is it?
Now you may be thinking, I can just use the Is Not Equal To operator here, like so:
<?php
if($have_bag!="yes"){
$take_bag="yes";
};
?>
And I’d be so proud of you, because yes, that’s exactly what you can do. In a conditional statement where we’re only checking one condition like the example above, the NOT operator doesn’t really become useful. But you can combine the AND, OR, and NOT operators to create as precise a combination of conditions as you’d like, and THAT’s where the NOT operator really shines. I’ll expand on the previous example, and create a few more conditions:
1) If you have a bag AND my bag has space, don’t take the bag. Or, if you have a spare hand and can carry the shoebox without a bag, don’t take the bag.
<?php
if(($have_bag=="yes" && $bag_has_space=="yes") || $can_carry_box=="yes"){
$take_bag="no";
};
?>
2) If you don’t have a bag, take the bag. OR, if you have a bag but(AND) the store’s bag is pretty, take the bag. OR, if you have a bag but(AND) there is not enough space, take the bag.
<?php
if(($have_bag!="yes") || ($have_bag=="yes" && $store_bag=="pretty") || ($have_bag=="yes" && $bag_has_space!="yes")){
$take_bag="yes";
};
?>
3) If neither is the store’s bag pretty nor is the box very heavy, don’t take the bag.
<?php
if(!($store_bag=="pretty" || $box_weight=="heavy")){
$take_bag="no";
};
?>
I can go on and on, but it’s pointless if you get lost in the process. I suggest you go and start experimenting with some simple conditions, and build up the complexity each time you try it, until you’re capable of wielding superbly complex conditions to filter your code’s purposes. It also makes for some excellent shoe-shopping.
Finally! We’re done with operators. I know it may seem like a lot, but really, you don’t have to memorize everything right now. You can always refer back here as and when you need to use them, and eventually you’ll know them like the back of your own hand. In the next chapter I will be covering conditional statements more thoroughly, and I will also be introducing you to loops. Until then, happy coding, and if there are any questions or comments, please let me know in the comments below!
Other posts in the series
- Beginner PHP Chapter 4 - Conditional Statements - July 23, 2010
- Beginner PHP Chapter 3 - Operators (This post) - June 3, 2010
- Beginner PHP Chapter 2 – Functions and Variables - May 23, 2010
- Beginner PHP Chapter 1 – The Meet n’ Greet - April 16, 2010
