Mobile and web design development (Android, iPhone, WordPress)
Google+TwitterLinkedinFacebook
Subscribe
Homelookup table

Lookup table

Function lookup tables in PHP

I’ve don my share of coding in Assembly language and one of the constructs that is pretty efficient to use is lookup tables for calling subroutines or functions. One of the things I like PHP is its ability to do the same thing.

For example, if you want to perform exception/error handling based on a status code, you can use lookup tables instead of using a switch() construct. If you use a switch() construct, you’ll have something like:

switch( $status ) {
    case 0: do_action_1(); break;
    case 0: do_action_1(); break;
    default: do_default();
}

If you use a lookup table, your source code will have something like:

$lookup = array( 'do_action_1','do_action_2');

if ( $status >= 0 &amp;&amp; $status < count($lookup) ) {
    call_user_func($lookup[$status]);
}

I’m sure there are other uses of lookup tables and the combination of using array() and call_user_func() in PHP offers a lot of flexibility in coding.