PHP: Convert a negative number into a positive number.

This is a short tutorial on how to convert negative numbers into positive numbers using PHP. In this guide, we will show you how to use PHP’s abs function.

Take a look at the following snippet.

//For the sake of this tutorial, let us say that our variable contains -6
$ourNegativeNumber = -6;

//To convert this minus number into a positive number, we simply use PHP's abs function.
$positiveNumber = abs($ourNegativeNumber);

//Print it out onto the screen.
echo $positiveNumber;

//The result should be 6.

In the code above, we converted the number -6 to 6 using PHP’s abs function. The abs function will return the absolute number of a given variable.

In case you didn’t already know, an absolute value is the non-negative value of a number.

For example, the absolute “version” of -10 is 10.

Note that the abs function also works with float values and decimal numbers.

//A negative decimal number
$ourNegativeDecimal = -6.24;

//The abs function will also convert negative decimal numbers into positive decimals.
$positiveDecimal = abs($ourNegativeDecimal);

//Print out our float value onto the screen.
echo $positiveDecimal; //becomes 6.24

The return type from the abs function depends on the variable that you provide it with. For example, if you provide it with a float value, then the return type will also be a float. Otherwise, it will return an integer value.