PHP Math Operations. What You Need To Know About Math Operations in PHP

Posted by TotalDC

I guess we are on the roll. Last time we covered PHP functions and today another article about PHP and I thought let’s talk about math operations in PHP.

Performing Math Operations

Now you know that PHP has quite a few built-in functions, math related functions is no exception. PHP has several built-in functions to help you perform everything from simple math functions like addition and subtraction to advanced calculation. We already talked about basic mathematical operations in PHP operators article, but let’s check out more examples.

<?php
print 5 + 3; // Result: 8
print 5 - 2; // Result: 3
print 5 * 2; // Result: 10
print 5 / 2; // Result: 2.5
print 5 % 2; // Result: 1
?>

Every math operation is performed in certain order. Generally multiplication and division are performed before addition and subtraction. But as you may know parentheses can alter this precedence. Expressions in parentheses are always done first regardless of the exact operation.

<?php
print 5 + 4 * 10;         // Result: 45
print (5 + 4) * 10;       // Result: 90
print 5 + 4 * 10 / 2;     // Result: 25
print 8 * 10 / 4 - 2;     // Result: 18
print 8 * 10 / (4 - 2);   // Result: 40
print 8 + 10 / 4 - 2;     // Result: 8.5
print (8 + 10) / (4 - 2); // Result: 9
?>

Now that we are done with how math works let’s look at some built-in PHP functions that are most used in performing mathematical operations.

Find The Absolute Value Of A Number

The absolute value can be found using the abs() function. Let’s look at the example:

<?php
print abs(5);    // Result: 5 (integer)
print abs(-5);   // Result: 5 (integer)
print abs(4.2);  // Result: 4.2 (double/float)
print abs(-4.2); // Result: 4.2 (double/float)
?>

As you see if given number is negative, the returned value is positive and if the number is positive you simply get that number.

Round A Fractional Value Up Or Down

If you want to round a fractional value up to the next integer value you should use ceil() function. And if you want to round a fractional value down to the next integer you use floor() function. Let’s look at the example to make things clear.

<?php
// Round fractions up
print ceil(4.2);    // Result: 5
print ceil(9.99);   // Result: 10
print ceil(-5.18);  // Result: -5
 
// Round fractions down
print floor(4.2);    // Result: 4
print floor(9.99);   // Result: 9
print floor(-5.18);  // Result: -6
?>

Find The Square Root Of A Number

If you want to find the square root of a number you should use sqrt(). Keep in mind that if you are trying to find square root of a negative number the result will be NaN.

<?php
print sqrt(9);   // Result: 3
print sqrt(25);  // Result: 5
print sqrt(10);  // Result: 3.1622776601684
print sqrt(-16); // Result: NAN
?>

Generate A Random Number

Ok, i can bet that this function will be used very often. I’m talking about rand(). This function is used to generate a random number. You can specify range by passing min and max arguments in order to determine range of your random number. If rand() function is called without min, max range, it will return random number between 0 and getrandmax(). The getrandmax() function shows the largest possible random value. So if you want your number to be in specific range, don’t forget to declare min and max arguments.

<?php
// Generate random number
print rand() . "<br>";
print rand() . "<br>";
 
// Generate random number between 1 and 10 (inclusive)
print rand(1, 10) . "<br>";
print rand(1, 10) . "<br>";
?>

Convert Decimal Numbers To Binary And Vice Versa

The decbin() function is used to convert a decimal number into binary number and bindec() converts number from binary to decimal.

<?php
// Convert Decimal to Binary 
print decbin(2);    // Result: 10  
print decbin(12);   // Result: 1100  
print decbin(100);  // Result: 1100100
 
// Convert Binary to Decimal
print bindec(10);       // Result: 2 
print bindec(1100);     // Result: 12  
print bindec(1100100);  // Result: 100
?>

Convert Decimal Number To Hexadecimal And Vice Versa

The dechex() function can be used to convert a decimal number into hexadecimal. And hexdec() function is used to convert a hexadecimal number to a decimal number.

<?php
// Convert decimal to hexadecimal 
print dechex(255);  // Result: ff
print dechex(196);  // Result: c4
print dechex(0);    // Result: 0
 
// Convert hexadecimal to decimal
print hexdec('ff');  // Result: 255
print hexdec('c4');  // Result: 196
print hexdec(0);     // Result: 0
?>

Convert Decimal Number To Octal And Vice Versa

The decoct() function is used to convert a decimal number into octal representation. And octdec() function is used to convert octal number to decimal number.

<?php
// Convert decimal to octal 
print decoct(12);   // Result: 14
print decoct(256);  // Result: 400
print decoct(77);   // Result: 115
 
// Convert octal to decimal
print octdec('14');   // Result: 12
print octdec('400');  // Result: 256
print octdec('115');  // Result: 77
?>

Convert A Number From One Base System To Another

The base_convert() function can be used to convert a number from one base system to another. or example, you can convert decimal (base 10) to binary (base 2), hexadecimal (base 16) to octal (base 8), octal to hexadecimal, hexadecimal to decimal etc.

This function accepts three parameters: the number to convert, the base it’s currently in, and the base it’s to be converted to. The basic syntax looks like this:

base_convert(number, frombase, tobase);

Number can be either and integer or a string representing an integer. Worth noticing that both frombase and tobase have to be between 2 and 36 inclusive.  Digits in numbers with a base higher than 10 will be represented with the letters a-z, where a means 10, b means 11 and z means 35. Here’s a simple example to show how this function works:

<?php
// Convert decimal to binary
print base_convert('12', 10, 2);  // Result: 1100
// Convert binary to decimal
print base_convert('1100', 2, 10);  // Result: 12
 
// Convert decimal to hexadecimal
print base_convert('10889592', 10, 16);  // Result: a62978
// Convert hexadecimal to decimal
print base_convert('a62978', 16, 10);  // Result: 10889592
 
// Convert decimal to octal
print base_convert('82', 10, 8);  // Result: 122
// Convert octal to decimal
print base_convert('122', 8, 10);  // Result: 82
 
// Convert hexadecimal to octal
print base_convert('c2c6a8', 16, 8);  // Result: 60543250
// Convert octal to hexadecimal
print base_convert('60543250', 8, 16);  // Result: c2c6a8
 
// Convert octal to binary
print base_convert('42', 8, 2);  // Result: 100010
// Convert binary to octal
print base_convert('100010', 2, 8);  // Result: 42
 
// Convert hexadecimal to binary
print base_convert('abc', 16, 2);  // Result: 101010111100
// Convert binary to hexadecimal
print base_convert('101010111100', 2, 16);  // Result: abc
?>

Worth noticing that the base_convert() function will return a string value.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: