Operating with Operators
Posted on 24. Feb, 2010 by admin in Basics
In the previous tutorial we stored a number in a variable and printed it. Let’s take this concept to another level with PHP operators. Basically, operators are just a technical way of saying adding, subtracting, multiplying, etc. PLEASE NOTE THAT I HAVE REMOVED THE HTML TAGS. YOU STILL NEED THEM!
<?php //Adds 5+7. Variable value is 12. $add = 5+7; //Subtract 9-3. Variable value is 6. $subtract = 9-3; //Multiply 10*10. Variable value is 100. $multiply = 10*10; //Divide 32/2. Variable value is 18. $divide = 32/2; //Modulus(Also known as remainder) 10/3. Variable value is 1. $modulus = 10%3; ?>
See how helpful comments can be in explaining code? Instead of explaining each line of code to you, I can simply add a comment to tell what it does in plain and simple English.
You can also place a variable on the right side of the equal sign to perform operations on it.
<?php //The variable's starting value of 10 $variable = 10; //Lets add 5 to it to make it 15 $variable = $variable + 5; //Subtract 9 to make it 6 $variable = $variable -9; //Print out the final answer, 6 echo $variable; ?>
Pretty simple, huh? Well, we can make this even simpler. You can combine the operator with the equal sign to get what is called an assignment operator. You use it when you want to modify the existing variables value, just like before. You achieve the same result as the code above, but with fewer keystrokes. You can also use increment (++) and decrement(–) to move the value up or down by one, respectively.
<?php //The variable's starting value of 10 $variable = 10; //Lets add 5 to it to make it 15 $variable += 5; //Subtract 9 to make it 6 $variable -= 9; //Multiply by 10 to make it 60 $variable *= 10; //Divide by 5 to make it 12 $variable /= 5; //Find the remainder of 12/5 to make it 2 $variable %= 5; //Increment to make 3 $variable++; //Decrement to make 2 $variable--; //Print out the final answer, 2 echo $variable; ?>
It’s a bunch to take in, so I suggest you play around with it for a few minutes before you move onto the next tutorial.

