Php – What’s quicker, an array lookup (including array build) or an IF stack


I was wondering which was better:

$lookup = array( "a" => 1, "b" => 2, "c" => 3 );
return $lookup[$key];


if ( $key == "a" ) return 1
else if ( $key == "b" ) return 2
else if ( $key == "c" ) return 3

or maybe just a nice switch…

case "a": return 1;
case "b": return 2;
case "c": return 3;

I always prefer the first method as I can separate the data from the code; At this scale it looks quite silly but on a larger scale with thousands of lines of lookup entries; How much longer is PHP going to take building an array and then only checking maybe 1 or 2 entries per request.

I think it'd have to be tested and clocked, but I'd say the bigger and more complicated the array the slower it's going to become.

PHP Should be able to handle lookups faster than I can in PHP-code, but building the array in the first place surely takes up a lot of time.

Best Solution

For anything with measurable performance (not only 3 entries) lookup is fastest way. That's what hash tables are for.