PHP Math Functions

PHP provides many built-in functions to perform different kinds of mathematical operations.

PHP Math: abs() function

The abs() function returns the absolute value of the given input. Typically PHP abs() returns integer value but if you provide float value, the function will return float number.

Syntax

number abs ( $number )

Example

<?php
echo abs(5)."<br/>"; // 5 (integer)
echo abs(-5)."<br/>"; // 5 (integer)
echo abs(7.2)."<br/>"; // 7.2 (double/float)
echo abs(-7.2)."<br/>"; // 7.2 (double/float)
?>

Output

5
5
7.2
7.2

PHP math: ceil() function

The ceil() is used to round the value up to the next higher integer value.

Syntax

float ceil ( float $value )

Example

<?php
echo ceil(5.4)."<br/>";// 6
echo ceil(8.22)."<br/>";// 9
echo ceil(-5.8)."<br/>";// -5
?>

Output

6
9
-5

PHP math: floor() function

The floor() function returns the next lower value of the given fractional number.

Syntax

float floor ( float $value )

Example

<?php 
echo floor(5.4)."<br/>";// 5
echo floor(8.22)."<br/>";// 8 
echo floor(-5.8)."<br/>";// -6 
?>

Output

5
8
-6

PHP math: sqrt() function

The sqrt() function is used to perform the square root of the given argument.

Syntax

float sqrt ( float $arg )

Example

<?php
echo sqrt(25)."<br/>";// 5
echo sqrt(49)."<br/>";// 7
echo sqrt(8)."<br/>";// 2.8284271247462
?>

Output

5
7
2.8284271247462

PHP Math: decbin() function

The decbin() function converts into binary for the given decimal number. It always returns binary number as a string.

Syntax

string decbin ( int $number )

Example

<?php
echo decbin(4)."<br/>";// 100
echo decbin(11)."<br/>";// 1011
echo decbin(26)."<br/>";// 11010
?>

Output

100
1011
11010

PHP Math: dechex() function

The dechex() function is used to convert decimal number into hexadecimal. It returns hexadecimal representation of given number as a string.

Syntax

string dechex ( int $number )

Example

<?php 
echo dechex(4)."<br/>";// 4 
echo dechex(11)."<br/>";// b 
echo dechex(24)."<br/>";// 18
?>

Output

4
b
18

PHP Math: decoct() function

The decoct() function is used to convert decimal numbers into octal. It returns octal representation of given number as a string.

Syntax

string decoct ( int $number )

Example

<?php
echo decoct(4)."<br/>";// 4
echo decoct(12)."<br/>";// 14
echo decoct(25)."<br/>";// 31
?>

Output

4
14
31

PHP Math: bindec() function

The bindec() function is used to converts binary number into decimal.

Syntax

number binder ( string $binary_string ) 

Example
<?php 
echo bindec(110)."<br/>";// 6 
echo bindec(1110)."<br/>";// 14 
echo bindec(1111)."<br/>";// 15 
?>

Output

6
14
15

 

Please get connected & share!

Advertisement