SCRIPTING:

Dena Doster

PHP NUMBERS FUNCTIONS AND MANAGEMENT
A complete overview of all the PHP functions to manipulate Numbers.
Detailed documentation on arguments, returned values, some behaviour in case of inconsistent arguments.
A few copy & paste functions to improve a few default managements may be provided along.
August 2003
{ @ }
    No Scroll? »

The model above is Dena Doster
LOADS OF DENA DOSTER ON THE NET


PHP FUNCTIONS FOR NUMBERS
Nearly 100% comprehensive list


is_integer & is_double & is_long & is_numeric
ARGUMENTS
RETURNS
is_integer( number )
is_double( number )
is_long( number )
is_numeric( number )
boolean
USAGE
These function checks whether a variable is a number. Although PHP is not a so called strongly typed language, none the less it can distinguish among integer, double (fractional numbers), and long numbers. Actually the is_long function is just regarded, also by Leon Atkinson, a s a mere alias of is_integer, so we can say that indeed Php discriminates only between integer and floating numbers:
if(is_integer(2.5)){print 'integer';}
//prints: nothing, returning boolean false
if(is_integer(2)){print 'integer';}
//prints: integer, returning boolean true
if(is_double(2.5)){print 'double';}
//prints: double, returning boolean true
if(is_double(2)){print 'double';}
//prints: nothing, returning boolean false

 
Actually the best way to check the numeric nature of a number is to use is_numeric: this function, in fact, would return true also if the number is actually a numeric string: that is, a number but in between quotes. PHP has no javascript-like method (as parseInt or parseFloat) to turn a numeric string into a number, but that is not necessary actually: the so called php type juggling allows a numeric string to be summed to a number by simply turning both strings into proper numbers as soon as you include a mathematical operation sign:
print ('12'+4); /*prints: 16, although 12 was in between quotes and could have been mistaken for a string*/
So I may suggest to you to use is_numeric always to see whether a number is such:
if(is_numeric(2.5)){print 'it is';}
//prints it is
if(is_numeric('2.5')){print 'it is';}
//prints it is
if(is_numeric(21)){print 'it is';}
//prints it is

If you want to extract a numerical section from a string which may have leading or trailing letters you may use a regular expression like preg_match_all. Here is anyway a function that does that: takes in as its only argument a number (or a stringed version of it) or a string which may have either trailing or leading letters: it strips them all and just return the number (in the same format it was passed: if was passed a s a string it returns it as a string, if it was a number as a number, and if it finds no number it returns boolean false):

Example:
$string='aa55.08aa';
print getnum($string);
//prints: 55.08

number_format
ARGUMENTS
RETURNS
number_format( number, number, string, string )
string
USAGE
This is the function used to yield a specific numerical format out of an input number.
The only mandatory argument is the first, which is the input number. It returns a string.
If the input number is a stringed version of a number (in between quotes, that is), it works as well, and of course it still returns the output in the string version.
If the first argument is absent a warning may be generated and what is returned is NULL.
 
The second argument must be a number and represents the amount of floating digits after the possible dot (the fractional part, that is) which you want to be included: it defaults to zero, so by default it strips off all the digits after the integral section, therefore this function is sort of an emulation of the javascript parseInt method too.
print number_format(11.044);
//prints: 11
print number_format(11.044, 2);
//prints: 11.04

Be warned that if this second argument meant to represent the amount of allowed fractional digits exceeds the amount of available ones, it will add as many zeroes to the fractional part until the limit is reached:
print number_format(11.51, 6);
//prints: 11.510000


The last two arguments are optional as well. They must be strings and the former (that is, the third argument) is the symbol used to separate the fractional part from the integer one (it replaces the dot, that is), and the latter argument (the fourth) is the separator which must be used to separate the thousands. The setback is that if you use one of them you must include the other one too or an error is returned (yeah, slightly irrational):
print number_format(11.044, 2, '-', '/');
//prints: 11-04

print number_format(11.044556, 6, '-', '/');
//prints: 11-044556

print number_format(11000000.044556, 6, '-', '/');
//prints: 11/000/000-044556

ceil & floor & round & abs
ARGUMENTS
RETURNS
ceil( number )
floor( number )
round( number )
abs( number )
number
USAGE
These functions take in a number, but even if it is a stringed number they work as well. They always return a number though.

Given a floating number ceil rounds it to the highest close integer:
print ceil(1.3);
//prints: 2
print ceil(1.0)
//prints: 1, for zeroes alone do not matter!


Given a floating number floor rounds it to the lower close integer:
print floor(1.3);
//prints: 1
print floor(1.9)
//prints: 1


Given a floating number round rounds it to the closest integer:
print round(1.3);
//prints: 1
print round(1.8)
//prints: 2


Given a number either positive or negative, abs returns such number stripping the plus or minus leading sign: returns the absolute value, that is:
print abs(-14);
//prints: 14

pi & pow & sqrt & log & log10
ARGUMENTS
RETURNS
pi( )
pow( number, number )
sqrt( number )
log( number )
log10 ( number )
number
USAGE
pi takes in no argument, it just returns:
3.1415926535898

pow raises the first argument number to the power of the second number; sqrt takes one argument alone and returns the square root of such number - oddly enough no apparent function is provided to draw higher roots. None the less you can draw the X root of any number N by using pow and powing to the reciprocal of X: that is:
$N=729;
$E=3;
$aRoot=pow($N, 1/$E);
//returns the cubic root of 729, which is 9


log and log10 are the two functions to generate logarithms (a feature somewhat no longer necessary with the introduction of computers for logarithms basically just make calculations much faster for humans).

sin & cos & tan & asin & acos & atan & deg2rad & rad2deg
ARGUMENTS
RETURNS
all get one number as argument
number
USAGE
These are the trigonometric functions. If you do not know what sine, cosine, tangent, arccosine, arccosine, arctangent and radians and degrees are I may be allowed to say that one of the best and most clear and most comprehensive files online about them is located right at unitedscripters and can be reached clicking here.
Once you know what they are what these functions are for would be absolutely obvious. Please refer to the file linked above if you don't.

Of course like in all programming languages the trigonometric functions take in the numerical argument representing the degree as expressed in radians, and (as far as asin and acos and atan are concerned for only these returns degrees whereas sin and cos and tan return ratios - again, same file) they return the value expressed in radians as well. Consequently to convert degrees into radians use deg2rad, and rad2deg for the vice-versa:

print sin(deg2rad(90));
//prints: 1

print rad2deg(asin(1));
//prints: 90

base_convert & dechex & hexdec
ARGUMENTS
RETURNS
base_convert(number, number, number)
dechex(number)
hexdec(string)
base_convert, hexdec: number
dechex: string
USAGE
base_convert takes in a number (also a stringed number is good) and converts it from the base given as the second argument into the base given as its second argument. I assume, of course, you know what a base conversion is. The bases allowed are up to base 36 included:
print base_convert(1100, 2, 10);
//prints: 12


to perform hexadecimal conversions use dechex and hexdec; dechex takes as argument a number, returns a string; hexdec takes as argument a string, returns a number:
print dechex(255);
//prints: ff

print hexdec('ff');
//prints: 255

bcadd & bcsub & bcmul & bcdiv & bcpow & bcsqrt
ARGUMENTS
RETURNS
bcadd(number, number, digits)
bcsub(string,string, digits)
bcmul(string,string, digits)
bcdiv(string,string, digits)
bcpow(string,string, digits)
bcsqrt(string, digits)
string
USAGE
All these functions return a string although they may take in also a number: the reason for this is that they are the set of functions meant to perform operations on numbers whose length is arbitrary (from zero until whatever amount of digits, even 1000 or more): such numbers given limitations inherent to all computers cannot be handled as numbers but must be turned into strings and the calculations must be performed lot by lot - therefore the stringed version of the number is returned. Also, it is very likely that if the number is too long, it is already passed as a string to override the limits that computer have to store too many digits expressed as numbers (whereas no limit is in place when you store a string: it could be as long as a book!).
Be warned about what Leon Atkinson says in his Core Php Programming:
"These functions are part of the binary distribution for windows, but they are not activated by default for other operating systems. If PHP reports these functions as being unrecognized you may need to recompile PHP using the -enable-bcmath option."
All these functions take in one (bcpow and bcsqrt) or two numbers (or, of course, stringed version of numbers) and perform sum (bcsum), subtraction (bcsub), multiplications (bcmul), divisions (bcdiv), powing (bcpow) and square roots (bcsqrt) - as far as square roots are concerned, oddly enough only squared roots can be drawn and not higher ones.
All these functions take a third argument which must be a number and represents the amount of digits you may want to have in any possible fractional part; such argument is sort of mandatory if you want to see the decimal part: by default it is zero, in fact - that is, no floating part whatsoever is shown:
print bcsqrt(2,1002);
the above prints the endless square root of 2 up to 1002 decimal digits (it is endless for it is a proved irrational number. The white spaces are added by me, splitting the floating output with chunk_split):

To get the X root of number N (that is, a root which is not necessarily and just the square root) see the sqrt function comment: as you'll see there you can use btpow here in a similar manner, that is.

bccomp & bcmod & bcscale
ARGUMENTS
RETURNS
bccomp(string, string, digits)
bcmod(string, string)
bcscale(number)
string
USAGE
As for the section above, be warned about what Leon Atkinson says in his Core Php Programming:
"These functions are part of the binary distribution for windows, but they are not activated by default for other operating systems. If PHP reports these functions as being unrecognized you may need to recompile PHP using the -enable-bcmath option."
bccomp compares the first argument (number or stringed number) with the second: it takes in for the comparison as many floating digits as you specify in the third argument (which defaults to zero, namely considers no floating digits by default) and returns:
  • 0: if they are equal
  • 1: if the first argument is bigger than the second
  • -1: if the first argument is smaller than the second
print bccomp('2342238009.00009', '2342238009.00008', 4);
//prints: 0, for it stops at the 4th floating digit

print bccomp('2342238009.00009', '2342238009.00008', 5);
//prints: 1


bcmod returns the modulus, namely the remainder of a division.
bcscale sets for the current script the amount of digits (the amount of them, their range, or scale) that should be taken in whenever you use a bc family functions throughout the current script, namely either these ones or those in the section above:
bcscale(3);
print bcadd('12.33451', '1.034905');
//prints: 13.368

Of course, if within a bc function you set a different scale, the last scale would override the global one for that specific instance in case.

srand & mt_srand & rand & mt_rand & & max & min & getrandmax & mt_getrandmax & uniqid
ARGUMENTS
RETURNS
srand(number),
mt_srand(number)
rand(number, number)
mt_rand(number, number)
max(number, number)
min(number, number)
getrandmax, mt_getrandmax: no arguments uniqid(string)
srand, mt_srand: NOTHING
rand, mt_rand, max, min, getrandmax, mt_getrandmax: number
uniqid: string
USAGE
When you generate random numbers the computer needs what it is named a seed from which it generates a random number. You do have to feed this seed if you want to be quite sure your script would keep generating different random numbers at each call, othewise always the same random numbers will be generated throughout the session: the functions that seed the random process are srand or mt_srand (you can consider them equivalent in their purpose. mt_srand uses a seed called Mersenne Twister).

To call in these functions pass to them as their argument something volatile enough to be always different: usually the time in milliseconds gets employed after the following formula:
mt_srand( (double)microtime()*1000000 );
//or, of course, the same with srand:
srand( (double)microtime()*1000000 );


If you feed by mt_srand you then have to generate casual numbers by mt_rand.
If you feed by srand, you then have to generate casual numbers by rand.

NOTE: srand (and not mt_rand) is always used when you want to feed the function named shuffle.

In fact, without feeding them both rand and mt_rand might keep generating the same number; also, rand and mt_rand needs the two mandatory arguments representing the minimum and the highest random number you want to get:
srand( (double)microtime()*1000000 ); //fed the seed
print rand(0,10);
//prints a different number each time between 0 and 10 included


max and min return the highest and the lowest number among two numbers passed as arguments.

getrandmax and mt_getrandmax tell you which is the bigger random number that can be generated. On my platform:
mt_getrandmax prints: 2 147 483 647
getrandmax prints: 32 767
Consequently, the mt family is more powerful.

uniqid generates a random alphanumeric string. Such string is always 13 chars long. If you include in uniqid an argument, such argument would be prefixed to such 13 chars. Actually, such argument is mandatory or a warning ensues: so always provide it, even if only as an empty string: ''. Since the most volatile part of the generated id is the segment of the last 6 numbers, you may want to consider including as argument a random number:
mt_srand( (double)microtime()*1000000 ); //fed the seed
print uniqid( mt_rand(0,1000000000) );

If you want to exclude some of the first numbers generated by uniqid because they appear too static, you may use substr
$id=substr( uniqid(''), 7 );

mt_srand( (double)microtime()*1000000 ); //fed the seed
$id.=mt_rand(0,1000000000);

print $id;

Variations on this theme could be getting a long string of chars and then recursively select out of it a few randomly:


The function above named makeid generates a random extraction of 7 elements from a list of chars and additionally randomly uppercases them. Of course, such a string could be prepended to the last segment of an uniqid as we do in the example above. The function needs no arguments, but if you pass them they must be as follows:
  • $rounds: an integer, represents the amount of rounds you want to iterate while picking random chars, namely determines the length of the pre pended casual string. Defaults to 7 chars.
  • $addid: defaults to 1, pass it as zero if you want to bypass it: it adds a uniqid to the generated chars.
  • $idFrom: a number, defaults to 7 and determines which chars from the uniqid (if generated, namely if $addid is 1) must be taken in: 7 means only the substring of the generated uniqid from the 7th char onward to its 13th (that is, 7 chars of the uniqid).
  • $chars: a list of chars as a string: defaults to the alphabet plus numbers from 0 to 9. You don't need to discriminate between uppercase and lowercase for the function already uppercases and lowercases randomly. If this argument is an Array, no error ensues and the function would work it out by itself.
  • $splitter: a string just representing the splitter argument by which $chars has to be splitted (if it is a string, otherwise this passage gets skipps if $chars was an array). Defaults to an empty string, namely divides char by char in the set of subsequent chars of $chars.