Performing Math Operations

PHP has several built-in functions that help you perform anything from simple additions or subtraction to advanced calculations. You’ve already seen how to perform basic mathematical operations in PHP operators chapter. Let’s check out one more example:


Every math operation has a certain precedence level; generally multiplication and division are performed before addition and subtraction. However, parentheses can alter this precedence; expressions enclosed within parentheses are always evaluated first, regardless of the operation’s precedence level, as demonstrated in the following example:

Generate a Random Number

The rand() function can be used to generate a random number. You can optionally specify a range by passing the min, max arguments, as shown in the following example:


If rand() function is called without the optional min, max arguments, it returns a pseudo-random number between 0 and getrandmax(). The getrandmax() function show the largest possible random value, which is only 32767 on Windows platform. So, if you require a range larger than 32767, you may simply specify the min and max arguments.