25

I would like to ask how I can get the length of digits in an Integer. For example:

$num = 245354;
$numlength = mb_strlen($num);

$numlength should be 6 in this example. Somehow I can't manage it to work?

Thanks

EDIT: The example code above --^ and its respective method mb_strlen(); works just fine.

supersize
  • 13,764
  • 18
  • 74
  • 133

12 Answers12

74

Maybe:

$num = 245354;
$numlength = strlen((string)$num);
Sergei Gorjunov
  • 1,789
  • 1
  • 14
  • 22
25

Accepted answer won't work with the big numbers. The better way to calculate the length of any number is to invoke floor(log10($num) + 1) with a check for 0.

$num = 12357;
echo $num !== 0 ? floor(log10($num) + 1) : 1; // prints 5

It has multiple advantages. It's faster, you don't do the casting of types, it works on big numbers, it works with different number systems like bin, hex, oct.

The equation does the logarithm with base 10 then makes the floor of it and adds 1.

This solution can work independently on the base, so if you want to calculate the length of binary or hex just change the base of the logarithm.

Working fiddle

Robert
  • 19,800
  • 5
  • 55
  • 85
  • 1
    I think you must put an if for **0**; it causes -INF in PHP7. – MAChitgarha Jun 30 '18 at 09:31
  • what would cause it? I've just checked it with PHP7 and it's working. – Robert Jun 30 '18 at 13:02
  • Maybe you've got wrong with your test. I've just tested with many PHP versions (even PHP4) using two online PHP testers; for the value of zero, the output is -INF. To be sure, try **log10(0) === -INF**; the answer would be 1. – MAChitgarha Jun 30 '18 at 19:28
  • 1
    I see now I didn't understand you, I'll edit the answer, thanks – Robert Jun 30 '18 at 22:04
  • 1
    The third expression in the ternary operator would be 1, not 0; because 0 has 1 digit! – MAChitgarha Jul 01 '18 at 14:08
  • 1
    This should be the accepted answer since the currently accepted answer doesn't work with big number – Luu Hoang Bac Oct 11 '19 at 08:53
  • you can wrap it with abs() – Robert May 23 '21 at 18:40
  • Actually, it does not, remember that 0156 is actually octal literal so the base of the logarithm should be 8. Even with decimal base the leading zeros are ignored and the valid number length is 3 – Robert Aug 03 '21 at 11:25
  • wouldn't it be simpler to do `ceil(log10($num))` instead? – Albert May 03 '22 at 15:10
  • @Albert it's not enough for example `echo ceil(log10(1));` is 0 :) – Robert May 04 '22 at 08:14
  • @Robert Yep. I originally though that the `+1` should have been outside of the `floor()` function and that you had made a mistake, so it didn't make sense within the context of what I was trying to accomplish, but now I understand. Thanks for clarifying! – Albert May 06 '22 at 19:08
2

The accepted solution presents a problem when evaluating negative numbers.

It works with a positive number:

$num = 245354;
$numlength = strlen((string)$num);
// Result: 6

But with a negative number, the (-) is added to the count:

$num = -245354;
$numlength = strlen((string)$num);
// Result: 7

Quick workaround:

$num = -245354;
$numlength = strlen((string)abs($num));
// Result: 6
1

More elegant way :)

ceil(log10($num));
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
1

You could also use some basic math!

$digits = (int)(log($num,10)+1) 

<?php
  $num = 123;
  $num2 = 1234;
  $num3 = 12345;

  function digits($num){
    return (int) (log($num, 10) + 1);
  }

  echo "\n $num: " . digits($num);  // 123: 3
  echo "\n $num2:" . digits($num2); // 1234: 4
  echo "\n $num3:" . digits($num3); // 12345: 5 
  echo "\n";
Carlos Vergara
  • 657
  • 6
  • 19
1

Another way to find out the length of a number in digits would be to divide the integer part of the number to 10 until it becomes 0.

Example:

2021/10 = 202.1 
202/10 = 20.2 
20/10 = 2 
2/10 = 0.2

Code:

function numberGetLength($number) {
     $count = 0;
     while (intval($number) > 0) {
        $number = intval($number) / 10;
        $count += 1;
     }
     return $count
}
0

Just using some version of (int)(log($num,10)+1) fails for 10, 100, 1000, etc. It counts the number 10 as 1 digit, 100 as two digits, etc. It also fails with 0 or any negative number.
If you must use math (and the number is non-negative), use:
$numlength = (int)(log($num+1, 10)+1);

Or for a math solution that counts the digits in positive OR negative numbers:
$numlength = ($num>=0) ? (int)(log($num+1, 10)+1) : (int)(log(1-$num, 10)+1);

But the strlen solution is just about as fast in PHP.

0

The following function work for either integers or floats (works with PHP7+):

function digitsCount($number): int
{
    $number = abs($number);
    $numberParts = explode(".", $number);

    return
        strlen($numberParts[0]) +
        (strlen($numberParts[1] ?? 0));
}
MAChitgarha
  • 3,728
  • 2
  • 33
  • 40
0

In PHP types are loosely set and guessed, if you want to see something as a string if it is an integer, float, and (i have not tried this) bool then @Gorjunav is the most correct answer.

Reset the variable as a string

$stringNum = (string) $num;

Then you can go anything string related you want with it! And vice-versa for changing a string to an int

$number = (int) $stringNum;

and so on...

0

count only integer value

  `<?php
        $n1 =12345;
        $n2 =123454.55;
        $n3 =12345564.557;
        echo "The Number you Type: ".$n1."<br>";
        $count = 0; 
        while ($n1 != 0)  
        { 
            $n1 = $n1 / 10;
            $n1 = intval($n1);
            ++$count; 
        } 
        echo "The Digit in a Number: ".$count;
    }
    ?>`
0
echo strlen((string) abs($num)); // using **abs** it'll work with negative integers as well  
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/27946938) – Oliver Hader Dec 28 '20 at 10:31
  • @OliverHader In what way is this a comment or otherwise not an answer? Sure, it is lacking an explanation, but that just makes it an answer worthy of downvoting. – Mark Rotteveel Dec 28 '20 at 11:15
  • Albeit the answer is correct, it is a duplicate of https://stackoverflow.com/a/58828674/2854140 (Nov 2019). The comment above stems from a StackOverflow template being used in review queues. Keeping the amount of answers low and focussed helps other users to identify a solution faster. Thanks for your understanding! – Oliver Hader Dec 28 '20 at 11:31
0

Tested in PHP 4.4.9 - 8.0.0

$array = array(-1, 0, -0, 1, 4, 9, 10, -10, 20, -20, 100, -100);
foreach( $array as $key => $num ){
    echo $key."\t{$num}\t=>\t".($num !== 0 ? floor(log10(abs($num)) + 1) : 1)."\n";
}
/* Output:
0   -1  =>  1
1   0   =>  1
2   0   =>  1
3   1   =>  1
4   4   =>  1
5   9   =>  1
6   10  =>  2
7   -10 =>  2
8   20  =>  2
9   -20 =>  2
10  100 =>  3
11  -100    =>  3
*/
TigeR
  • 1
  • 1
  • 2