Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a simple lookup table with PHP

Tags:

php

I often find myself needing a simple PHP lookup table where I don't want to bother using a database.

For instance, I might have:

1 stands for "Good"
2 stands for "Bad"
3 stands for "Ugly"

Two ways it could be implemented are shown below. Is one more efficient than the other? Is there any other more intuitive ways to implement this?

switch($code)
{
    case 1:$result="Good";break;
    case 2:$result="Bad";break;
    case 3:$result="Ugly";break;
    default:$result=NULL;
}

$array=array(1=>"Good",2=>"Bad",3=>"Ugly");
$result=$array[$code];
like image 983
user1032531 Avatar asked Jan 13 '23 15:01

user1032531


2 Answers

It's a matter of what are you going to do with your lookup.

  • If it's just a lookup of key -> value pairs - array is a way to go
  • If you want to perform different actions based on the key - it's actually a good use case for Strategy pattern - no case or array that way at all.

So, case option is inferior in most cases, as it is less scalable and not able to change in run time.

To simulate the default case, use something like

$result = in_array($key, $lookup) ? $lookup[$key] : $default;
like image 114
J0HN Avatar answered Jan 31 '23 06:01

J0HN


The second example. The main reason being that it's less code to write in new entries, but it's also more flexible code, and might be marginally faster. But to implement the default case from the break statement the 'lookup' line/function should look like:

$result = (isset($array[$code]) ? $array[$code] : NULL;
like image 21
Sammitch Avatar answered Jan 31 '23 04:01

Sammitch