PHP has the ability to handle numbers. Back in the PHP Variables tutorial we found that PHP has the ability to do arithmetic. Let’s explore this further.
1. If WampServer is not running, go ahead and start it. Then open your code editor, create a new file called numbers.php and save it to your “introduction” directory under c:\wamp\www
2. Type in the code below (with or without the commentary — your choice):
<html> <head> <title>PHP Numbers</title> </head> <body> 1 + 3 = <?php echo 1+3; ?><br /> 5 times 4 = <?php echo 5*4; ?><br /> 6 divided by 2 = <?php echo 6/2; ?><br /> </body> </html>
3. Save the file. In your Web browser, go to: http://localhost/introduction/numbers.php
Note that when using numbers, you do not place them inside of quotes. This lets PHP process the numbers as numbers. If we put them in quotes:
<html> <head> <title>PHP Numbers</title> </head> <body> 1 + 3 = <?php echo 1+3; ?><br /> 5 times 4 = <?php echo 5*4; ?><br /> 6 divided by 2 = <?php echo 6/2; ?><br /> Numbers inside of quotes: <?php echo "6-2"; ?><br /> </body> </html>
Reload the page in the browser. We see it says “6-2″ instead of doing the operation, which would output 4.
4. Let’s continue to build on our numbers.php file. You can mix in variables with numbers, like so:
<html> <head> <title>PHP Numbers</title> </head> <body> 1 + 3 = <?php echo 1+3; ?><br /> 5 times 4 = <?php echo 5*4; ?><br /> 6 divided by 2 = <?php echo 6/2; ?><br /> Numbers inside of quotes: <?php echo "6-2"; ?><br /> Using variables and numbers: <?php $num1 = 4; $num2 = 5; echo ((7 + 9 + $num1) / $num2); // This is 7 + 9 + 4, divided by 5, which should equal 4. ?> </body> </html>
Save and refresh. Try out different numbers and arithmetic to see the results.
5. Often in programming you may want to just add one or subtract one from something. For example, on a web page counter, you just want to add one every time someone visits a certain page. PHP provides a shortcut for this:
<html> <head> <title>PHP Numbers</title> </head> <body> 1 + 3 = <?php echo 1+3; ?><br /> 5 times 4 = <?php echo 5*4; ?><br /> 6 divided by 2 = <?php echo 6/2; ?><br /> Numbers inside of quotes: <?php echo "6-2"; ?><br /> Using variables and numbers: <?php $num1 = 4; $num2 = 5; echo ((7 + 9 + $num1) / $num2); // This is 7 + 9 + 4, divided by 5, which should equal 4. ?> <br /> Add one (increment): <?php $num1++; echo $num1; ?><br /> Subtract one (decrement): <?php $num2--; echo $num2; ?><br /> </body> </html>
Using “++” tells PHP to add one to the variable and using “–” tells PHP to take one away.
Go back to Building PHP Scripts.