Page 1 of 1

Array Lookup Table

Posted: Wed Nov 24, 2010 5:23 pm
by Jonah Bron
Hello, world!

A few months ago, one of the gurus (could have been PCSpectra, onion2k, not sure) here demonstrated the use of an array as a lookup table without actually have a huge array; it worked with conditions or something. Would someone kindly show that again? I tried to google it, and search the forum real quick, but didn't find anything right off.

Thanks.

Re: Array Lookup Table

Posted: Wed Nov 24, 2010 6:12 pm
by McInfo
Was it topic 112042? If not, I think there might have been another topic dealing with lookup tables shortly after that.

Re: Array Lookup Table

Posted: Wed Nov 24, 2010 6:24 pm
by Jonah Bron
Yes, that's it, thank you. The format is a little confusing though, I'll have to experiment with it. :)

Edit: Ah, I see. It just evaluates those conditions and the result is the key. So it's either 0 or 1. The last wrong one would be at index 0, and the last true one would be at index 1. That's cool.

Re: Array Lookup Table

Posted: Mon Nov 29, 2010 4:23 pm
by Jonah Bron
I see an advantage of a Switch statement over this, and that is all conditions are checked, not just enough to get by.

Re: Array Lookup Table

Posted: Tue Nov 30, 2010 6:40 am
by Weirdan
Jonah Bron wrote:I see an advantage of a Switch statement over this, and that is all conditions are checked, not just enough to get by.
I don't think I'm following. In switch(true) {...} the first condition that evaluates to true would be executed, ignoring other conditions. In logical gate (let's call it like this) all conditions would be evaluated and the last evaluated to true would be used. To clarify, I mean something like this:

Code: Select all

function switch_switch($x, $y) {
   switch (true) {
        case $y >= 100           : return 100 + $x;
        case $y>= 50 && $y < 100 : return 50 + $x;
        case $y >= 1 && $y < 50  : return $y + $x;
        case $y < 1 : default    : return 0;
   }
}
function logicalGate_switch($x, $y) {
    $answerMap = array(
        $y < 1                  => 0,
        $y >= 1 && $y < 50      => $y + $x,
        $y >= 50 && $y < 100    => 50 + $x,
        $y >= 100               => 100 + $x,
    );
 
    return $answerMap[true];
}

Re: Array Lookup Table

Posted: Tue Nov 30, 2010 10:52 am
by Jonah Bron
That's exactly what I mean. Switch only checks enough to find a true one, while the lookup array method checks them all, which is obviously less efficient (although possibly negligible).

Re: Array Lookup Table

Posted: Wed Dec 01, 2010 3:55 pm
by VladSun
It has been discussed already:
viewtopic.php?f=50&t=113253