开发者

PHP substr - first parameter does not accept integers

开发者 https://www.devze.com 2023-02-08 19:30 出处:网络
The PHP substr function does not accept strings converted from integers... :P The situation If I leave the code like this, it works:

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 开发者_JS百科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?


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


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.


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号