Maybe this is a stupid question but what is faster?
<?php
function getCss1 ($id = 0) {
if ($id == 1) {
return 'red';
} else if ($id == 2) {
return 'yellow';
} else if ($id == 3) {
return 'green';
} else if ($id == 4) {
return 'blue';
} else if ($id == 5) {
return 'orange';
} else {
return 'grey';
}
}
function getCss2 ($id = 0) {
$css[] = 'grey';
$css[] = 'red';
$css[] = 'yellow';
$css[] = 'green';
$css[] = 'blue';
$css[] = 'orange';
return $css[$id];
}
echo getCss1(3);
echo getCss2(3);
?>
I suspect is faster the if statement but I prefere to ask!
getCss1(if statements) is roughly twice as fastgetCss2(array access) from my benchmarks.Results from
microtime():Per the comments, I agree about maintainability of using a translation array. Accessing
$cssdirectly is significantly faster given the removal of function overhead and array redeclaration.Note: Running PHP 5.3.15 on Mac OS X 10.8. I also varied call order
$idto test execution paths.