How to Calculate Length of Numbers in PHP


The simplest way to calculate the length of a number in digits is to divide the number by 10 until you are left with only a fractional result. However, there is a far more efficient way using the common logarithm (log10) function, since the common logarithm of any number, rounded down and with one added, is the length of that number in digits.

  • Open a text editor such as Notepad or your favorite PHP Integrated Development Environment (IDE).

  • Type the following simple program:



    function getLength($number) {

    $length = 0;

    if ($number == 0){

     $length = 1;

    } else {

    $length = (int) log10($number)+1;


    return $length;


    $number = 5000;

    echo getLength($number);


    This defines a function that will get the length of any number using the common logarithm method.

  • Save your work.

Related Searches


Promoted By Zergnet


You May Also Like

  • How to Format Phone Numbers in PHP

    Most web development applications save a 10-digit number in the database without any dashes or parentheses. Hypertext preprocessor (PHP) is a web...

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!