开发者

php loop doesnt work with $i assigned to a 21 digit number

开发者 https://www.devze.com 2023-04-07 13:25 出处:网络
I have a php loop like : for($i = $_GET[\'start\']; $i < $_GET[\'end\']; $i++){ echo $i; } when $i is assigned to something like 100000000000000000000 the script doesnt run and it retu开发者_高

I have a php loop like :

for($i = $_GET['start']; $i < $_GET['end']; $i++){

echo $i;

}

when $i is assigned to something like 100000000000000000000 the script doesnt run and it retu开发者_高级运维rns no errors!! is there anywway I can fix this?

thanks


The value you are using is too large for PHP to handle.

"The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value."

http://php.net/manual/en/language.types.integer.php

Here is the solution that I tested using strings instead of integers and it works:

$start = (string)$_GET['start'];
$end = (string)$_GET['end'];

for($i = $start; strcmp($i, $end); $i = bcadd($i, 1)){
    echo $i . "<br>";
}


First of all you need to specify which range of numbers your script should support.

Then you need to find the right data structures to handle the data, e.g. integer - or more likely in your case - gmp numbers.

Then you can just code. The for loop works as announced, you might want to not hard-code it against $_GET probably.


First, do not put $_GET['start'] and $_GET['end'] directly in your code.

Instead, assign these to variables and check to make sure they are numeric and in range.

For example: end cannot be less than start, etc...

for($i = $start; $i < $end; $i++){

echo $i;

}

Second, a number that large will hang your server.


Why not use the difference between start and end so your loop vars are smaller:

<?php

$min = 0;
$max = $_GET['end'] - $_GET['start'];
for($i = $min; $i < $max; $i++){
    echo $i + $_GET['start'];
}
0

精彩评论

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