Andrew Goldenberg
Andrew Goldenberg

Reputation: 21

count_chars in PHP where the number of characters is greater than 16

So for some reason when I use count_chars(11111111111111111111,3) I get back something to the effect of .1111111111111119

Is there a different way to count the occurences of each character in a string?

Here's some example code

            $value = 11111111111111111111; 
            $value = strval($value);
            $count = count_chars($value,3);
            print_r($count);

If I print out the result I get +.012E

Upvotes: 0

Views: 355

Answers (2)

Blaatpraat
Blaatpraat

Reputation: 2849

The problem here is, is that you're not using integers, but floating points.
And with floats that big, they will be shown in the scientific way (with the E).

So 11111111111111111111 becomes 1.1111111111111E+19 (in math this is the same number).
If you convert it to a string (cast, of strval()), it will take the second one here.
And because you will have 1.1111111111111E+19 as a string, you will get the output you give us.

Solution to this? You have a few, but they're not that good.
Best way I can think of, is using the number_format function:

$value = number_format($value, 0, '', '');

Instead if the strval() function.

The big problem here is, is that floating points are not precisly enough for this. You will get rounding problems. See more information here.

On my computer the string would become 11111111111111110656 because it rounds to 1111111111111111.0656.

If you know the length of the integer (16 in this case), you could use substr() for this, but again: it will only be a workaround.

Upvotes: 0

nospor
nospor

Reputation: 4220

If you want to count characters in string, give a string...

count_chars('11111111111111111111',3)

ps: and if you really want to count characters use mode 1

 $res = count_chars('1111111111111111111122333', 1);

 foreach ($res as $char => $number) {
  echo chr($char). ' ' . $number .'<br />';
 }

Upvotes: 1

Related Questions