1

The PHP substr function does not accept strings converted from integers... :P

The situation

If I leave the code like this, it works:

<?php

$key = '35110100840754000150550010000014301000000809';
echo substr($key, 35, -1);

?>

And the result is right:

00000080

The problem

But I get this key from an integer variable (from the database). So the result is null and similar to what I get from this code:

<?php

$key = 35110100840754000150550010000014301000000809;
echo substr($key, 35, -1);

?>

And the result is a blank string.

I tried everything, like (string) casting, substr($key."", 35, -1) , and it does not work.

Does anyone have any suggestions?

Paulo Coghi
  • 13,724
  • 14
  • 68
  • 90

5 Answers5

3

If the database is returning an integer value, then it's subject to the 32-bit (or 64-bit if you're on a 64-bit server) limitations. 35110100840754000150550010000014301000000809 way exceeds the max integer value for even a 64-bit server. It may be converted to a float, in which case you'll be losing accuracy.

Get your database query to cast it as a string, and that should solve your problem

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

The number is too big to be an integer in php, see the manual.

In you case, 35110100840754000150550010000014301000000809, will be something like 3.5110100840754E43 (give or take a few digits). As you start at position 35 (after the end of the string...), the result will be NULL.

jeroen
  • 91,079
  • 21
  • 114
  • 132
1

try to print $key after substr. You'll see that the number is already null after the function. The range of an integer is -2147483648 to 2147483647.

Apply a typecast in your value, converting to a string, strval() or (string)$key

0

strval() might work. Check this related SO post, dealing with strings and mysql in PHP: Converting an integer to a string in PHP

Community
  • 1
  • 1
Girish Rao
  • 2,609
  • 1
  • 20
  • 24
0

The root problem is that the number is converted to a float when you assign it because it is overflowing the integer value.

horatio
  • 1,426
  • 8
  • 7