PHP for the World Wide Web (Visual QuickStart Guide)
I l @ ve RuBoard |
PHP has a number of built-in functions for manipulating your mathematical data. I'll use a couple of them here to improve upon our numbers .php script and you can refer to the PHP manual, specifically the Mathematical Functions chapter, to learn about some of the others (see Appendix C, PHP Resources, regarding the PHP manual). One built-in mathematical function, you can use in your calculator script is round(). As its name implies, round() takes whatever number and rounds it to the nearest integer, using standard conventions: anything .50 and above is rounded up, anything below .50 is rounded down. The assumption is that you will be rounding a decimal, but attempting to round an integer will cause no problems (it just won't do anything, since rounding 2 results in 2). Some examples are: $Number = round(23.309); // $Number is equal to 23. $Number = round(23.51); // $Number is equal to 24. You can round a number to a particular decimal point by adding a second parameter to the equation. $Number = round(23.51, 1); // $Number is equal to 23.5. PHP has broken round() down into two other functions. The first, ceil(), rounds every number to the next highest integer and the second, floor(), rounds every number to the next lowest integer. Another function that our calculator page can make good use of is abs(), which returns the absolute value of a number. In case you do not remember your absolute values, it works like this: $Number = abs(-23); // $Number is equal to 23. $Number = abs(23); // $Number is equal to 23. In laymen's terms, the absolute value of a number is always a positive number. Two last functions which I'll introduce here are srand () and rand(). The latter is a random number generator and the first is a function which is used to seed rand(). You must use srand() before calling rand() in order to guarantee truly random numbers. The PHP manual recommends the following code: srand ((double) microtime() * 1000000); $RandomNumber = rand(); The manual itself is remarkably without explanation as to why you should use that exact line to seed the random number generator except to say that the creators of PHP 4 state that it guarantees the most random numbers. The rand() function can also take a minimum and maximum parameter if you would prefer to limit the generated number to a specific range. $RandomNumber = rand (0, 10); Of the functions mentioned here, you'll incorporate abs() and round() into numbers.php to protect against invalid user input. To use built-in mathematical functions:
|
I l @ ve RuBoard |