How to count number of digit included zero in php

user2388680 picture user2388680 · Jun 11, 2013 · Viewed 51.3k times · Source

I am working to count number of digit in PHP. I just want to count number of digit value for database.In first number have zero means , it won't take as a number for counting.

for example:

12  ==number of count value is 2
122 ==number of count value is 3

I can achieve this through function.here my function.

function count_digit($number)
{
    return strlen((string) $number);
}

$number = 12312;
echo count_digit($number); // 5

But I need to add zero for that number $num = 0012312; (zero-fill).

012 == number of count value is 3
0133 == number of count value is 4

Let me know how to solve it.

Answer

Kevin picture Kevin · Jun 11, 2013

If you wish the leading zeros to be counted too, you should assign it as a string and not as number.

Then, try to calculate the number of characters. This time, it will include the zeros. No need to type cast inside the function.

So, now your code will look like this:

function count_digit($number) {
  return strlen($number);
}

//function call
$num = "number here";
$number_of_digits = count_digit($num); //this is call :)
echo $number_of_digits;
//prints 5