Using WordPress ‘absint()’ PHP function

The absint() WordPress PHP function converts a value to a non-negative integer.

Usage

Let’s assume you have a variable that could potentially be a negative integer, a string, or a float, and you need to ensure it is a non-negative integer. Here’s how you can use absint():

$my_var = -15;
$non_negative = absint($my_var);
echo $non_negative;  // Outputs: 15

Parameters

  • $maybeint (mixed): The data you wish to have converted to a non-negative integer.

More information

See WordPress Developer Resources: absint()
Please note that due to a rounding error (PHP Bug #33731), you may sometimes get unexpected results for calculations.

Examples

Converting Negative Integers

This example shows how the function converts negative integers into their absolute values.

$my_var = -10;
$non_negative = absint($my_var);
echo $non_negative;  // Outputs: 10

Converting Non-integer Strings

Here, the function will return 0 when passing a non-integer string.

$my_var = "hello";
$non_negative = absint($my_var);
echo $non_negative;  // Outputs: 0

Converting Floats

For float values, the function will return the integer part of the absolute value.

$my_var = -20.33;
$non_negative = absint($my_var);
echo $non_negative;  // Outputs: 20

Handling Boolean and Null Values

The function returns 0 for false and NULL, and 1 for true.

$my_var = true;
$non_negative = absint($my_var);
echo $non_negative;  // Outputs: 1

Converting Arrays

For arrays, the function will return 1.

$my_var = array(10,20,30);
$non_negative = absint($my_var);
echo $non_negative;  // Outputs: 1