26 Aug 09 PHP Programming Tutorial: More Numbers (and functions)



This tutorial assumes you have completed the first PHP Numbers tutorial. In this article we will discuss more things PHP can do with numbers.

1. If WampServer is not running, go ahead and start it. Then open your code editor, create a new file called more-numbers.php and save it to your “introduction” directory under c:\wamp\www

2. Type in the code below (with or without the comments):

<html>
<head>
<title>PHP More With Numbers</title>
</head>
<body>
<?php
// Decimals are often referred to as "floats" in PHP.
$num = 2.73; // set a variable to use for this example.
?>
Ceiling: <?php echo ceil($num); // the "ceil" function will round your float up to the nearest number, which is 3. ?><br />
Floor: <?php echo floor($num); // the "floor" function will round your float down to the nearest number, which is 2. ?>
</body>
</html>

3. Save the file. In your Web browser, go to: http://localhost/introduction/more-numbers.php

Remember, PHP functions are basically just something that can perform a complicated operation for you. Eventually you can learn to create your own functions.

4. Here is a list of many more PHP number functions:

<html>
<head>
<title>PHP More With Numbers</title>
</head>
<body>
<?php
// Decimals are often referred to as "floats" in PHP.
$num = 2.73; // set a variable to use for this example.
?>
Ceiling: <?php echo ceil($num); // the "ceil" function will round your float up to the nearest number, which is 3. ?><br />
Floor: <?php echo floor($num); // the "floor" function will round your float down to the nearest number, which is 2. ?><br />
Round: <?php echo round($num, 1); // round to 1 decimal point. ?><br />
Square Root: <?php echo sqrt(9); // find the square root of 9, which is 3. ?><br />
Absolute Value: <?php echo abs(-20); // find the absolute value of -20, which is 20. ?><br />
Random Number: <?php echo rand(0,100); // generate a random number between 0 and 100. ?>
</body>
</html>

Save and reload the page in your browser, as always.

So we can see PHP offers many math functions, ranging from simple functions like addition, rounding, and random numbers; and functions for advanced math like tangent, logarithms and hyperbolic cosines. For a full list, check out PHP.net’s Math Functions page: http://www.php.net/manual/en/ref.math.php

Go back to Building PHP Scripts.

Leave a Comment