In PHP, you can get the length of an integer in the following ways:
- Converting to String and Calling
strlen()
; - Looping and Removing Digits Off the End;
- Calculating the Length Mathematically.
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
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.