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.
Array Lookup Table
Moderator: General Moderators
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
Re: Array Lookup Table
Was it topic 112042? If not, I think there might have been another topic dealing with lookup tables shortly after that.
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
Re: Array Lookup Table
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.
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.
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
Re: Array Lookup Table
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
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: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.
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];
}
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
Re: Array Lookup Table
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
It has been discussed already:
viewtopic.php?f=50&t=113253
viewtopic.php?f=50&t=113253
There are 10 types of people in this world, those who understand binary and those who don't