How to count number of digit included zero in php

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

//function call
$num = "012312";
$number_of_digits = count_digit($num); //this is call :)
echo $number_of_digits;

Make $num variable as a string.


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