开发者

Optimizing php conditionals

I have something like this:

<?php

$fix1 = XXXXXXX //Integer. Problem isn't here. Extracted automatically

$iffix1 = range(9000000,8000000);
$iffix2 = range(7999999,7888888);
...

//There're more iffix[XX]s, up to $iffix60

if($fix1 = in_array($iffix1)) {
    $var1 = 1;
} elseif($fix2 = in_array($iffix2)){
    $var2 = 2;
} ....

//I have 60 more elseifs as well

$result = $var1 * $fix1;
echo $result;

?>

The script is more complicated than that, but the question question only concerns this bit, Obviously, I开发者_运维技巧 get a low-memory error.

How can I fix this?


Without having any real clue what you're trying to do, here's some code:

$ranges = array(
    array(8000000,9000000),
    array(7888888,7999999),
    ...
);

$fix = 1234567;
$var = 0;

foreach($ranges as $range) {
    $var++;
    if($range[0] < $fix1 && $fix1 < $range[1])
        break;
}

echo $fix * $var


Instead of

if($fix1 == in_array($iffix1)){

you could do

if($fix1 >= 8000000 && $fix1 <= 9000000) {

That way, you could get rid of the $iffix-arrays, so you wouldn't have to store an array of ~1 million integers. In addition, it's much faster checking the two outer bounds, rather than checking each of the 1 million integers inside.

The same goes for the other conditions.


Your $iffix* arrays are really big, containg thousands of items, it seems -- which requires a lot of memory, and can explain you go beyond memory_limit, which causes a Fatal Error.

The wisest idea would be to re-think what you are doing, to avoid needing so much memory.

Else, you'll probably have to increase the value of memory_limit -- but if this is for a webapplication with many users, it's probably not a good idea...


Your whole design is questionable. Instead of having 60 variables, use an array of variables (Rule of thumb: If you have numbers in your variable name, you're doing it wrong). Instead of generating all the numbers in a range, use an object representing the range. And be aware that if ($fix1 = in_array(...)) actually changes the value of $fix1.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜