Last time we looked at text and strings in variables, in

this episode we’re going to continue with our exploration of

PHP variables and delve deeper into math and number handling

in PHP.

this episode we’re going to continue with our exploration of

PHP variables and delve deeper into math and number handling

in PHP.

Using numbers is not much different to using text and

strings, you allocate variables and fill them in, using

exactly the same techniques as you do using strings & text.

strings, you allocate variables and fill them in, using

exactly the same techniques as you do using strings & text.

Basic Operators

The standard arithmetic operators are available in PHP and

these are the same as in any other language:

these are the same as in any other language:

- + Addition of numbers (20+10)
- – Subtraction of numbers (20-10)
- * Multiplication of numbers (20*10)
- / Division of numbers (20/10)

When setting up or assigning variables, you can set the

initial value to the result of a mathematical equation, as

in the following example:

initial value to the result of a mathematical equation, as

in the following example:

$result = 2+2; // $result will be equal to 4

For subtraction and addition there’s also a very handy

shortcut or two which are great for loop handling, these

shortcuts are used by appending either a double + or a

double – after the variable name:

shortcut or two which are great for loop handling, these

shortcuts are used by appending either a double + or a

double – after the variable name:

- $a = 1; // $a equals to 1
- $a++; // $a equals 2
- $a–; // $a once again equals 1

The second operator can also be specified as ‘=num’ :

- $a = 1; // $a equals 1
- $a+=2; // $a equals 3
- $a-=2; // $a back to 1

Why would you want to use the shorthand form? Well it turns

out that using this method is great for loops and repetitive

commands (we’ll cover this more in a later article) such as

the for loop:

out that using this method is great for loops and repetitive

commands (we’ll cover this more in a later article) such as

the for loop:

for($count=0;$count<10;$count++) { // Repeat what ever goes here 10 times }

In that small example, we start at 0, and keep adding one to

$count as long as we are still less than 10.

$count as long as we are still less than 10.

An IMPORTANT note here, is that a lot of counting structures

in PHP start at 0, so in the previous example we are

counting from 0 to 9, which is 10 times round before it

stops. If we’d changed it to <11 in the middle part, we

would have actually performed 11 counts.

in PHP start at 0, so in the previous example we are

counting from 0 to 9, which is 10 times round before it

stops. If we’d changed it to <11 in the middle part, we

would have actually performed 11 counts.