How to Get the Length of an Integer in PHP?

Find out how to determine the length of an integer in PHP

In PHP, you can get the length of an integer in the following ways:

Converting to String and Calling strlen()

You can simply convert the integer to a string and call the strlen() function on it to find the total number of digits in the integer:

function intLen(int $num) {
    return strlen((string) abs($num));
}

echo intLen(0); // 1
echo intLen(-0); // 1
echo intLen(-12345); // 5
echo intLen(12345); // 5

Calling abs() on the integer is needed so that the minus symbol is removed from a negative integer prior to converting the integer to a string. Otherwise, the minus symbol (-) will be converted to string as is and will be counted in the string length.

Looping and Removing Digits Off the End

You can simply create a loop, and remove the last digit from the integer in each iteration till there are no digits left. In each iteration you can increment a counter, which would give you the total number of digits in the integer:

function intLen(int $num) {
    $len = 0;

    do {
        // take last digit off `$num`
        $num = (int) ($num / 10);
        // increment counter
        $len++;
    } while ($num !== 0);

    return $len;
}

echo intLen(0); // 1
echo intLen(-0); // 1
echo intLen(-12345); // 5
echo intLen(12345); // 5

Calculating the Length Mathematically

You can calculate the number of digits in an integer in the following way:

function intLen(int $num) {
    return ($num === 0)
        ? 1
        : ceil(log10(abs($num) + 1))
    ;
}

echo intLen(0); // 1
echo intLen(-0); // 1
echo intLen(-12345); // 5
echo intLen(12345); // 5

The check for 0 is necessary as log10(0) is equal to -INF.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.