PHPBuilder - Math & Number Handling in PHP - The ABCs of PHP Part 6 Page 3

# Math & Number Handling in PHP - The ABCs of PHP Part 6 - Page 3

by: PHP Builder Staff
|
April 21, 2009

Back to the barrel shifter
As you can see from the above examples, each column in a binary number is a multiplication of 2. The barrel shift, shifts binary bits in a number left and right and as a result is able to multiply and divide by 2 extremely fast. This is very handy if for example we are working with binary streams (such as if we where doing heavy number crunching in a compression system), and if we are chopping up and packing numbers.
Again, if this is a subject that interests you then there are many white papers and educational texts available that cover number theory, just be aware that if your divisions and/or multiplications are powers of two, or if you need to isolate only a single bit in a number then using the barrel shifter is an extremely efficient way to do it.
Number comparisons
In any computer language, the ability to check numbers that are in a given range is a must. You saw it earlier in the example of a for loop, and like loops in general we'll cover decisions in more detail when we cover loops and decisions in a later article, for now though we check ranges by using the following operators:
• \$a < \$b; // Is \$a less than \$b
• \$a > \$b; // Is \$a greater than \$b
• \$a => \$b; // Is \$a equal to or greater than \$b
• \$a =< \$b; // Is \$a equal to or less than \$b
• \$a == \$b; // Is \$a equal to \$b
Normally you would use these in an "if" statement similar to the following:
```	if(\$a > \$b)
{
// Do stuff if a is greater than b
}
else
{
// Do stuff if it's not
}
```
Summary
In this episode we've looked at basic math operations in PHP, and had a recap on binary. As with strings and text there is a huge number of functions that operate on numbers.
There are functions to generate random numbers, or do complex math using sines & cosines.
As always I encourage you to look at the appropriate sections in the PHP Manual, and experiment with what you find there. Remember half of the fun of programming is breaking things, then learning how to fix them.
Until next time Shawty

Comment and Contribute

## Your comment has been submitted and is pending approval.

Author:

Comment:

Comment:

(Maximum characters: 1200). You have characters left.