Write good PHP - Lookup-arrays
Joe 🏴
Posted on February 14, 2021
You have a list of potential values to return, dependent on a value to evaluate. A super common operation, right? You'll instantly think, chuck in an if statement, or even a switch, and call it a day - let's see an example. We want to return the relatives name based on the relation (Does anyone else forget names easily??):
$relative = $_GET['relative'];
if($relative == 'mother') {
return 'Harriet';
}
if($relative == 'father') {
return 'Robert';
}
if($relative == 'daughter') {
return 'Rachel';
}
if($relative == 'grandmother') {
return 'Audrey';
}
// imagine 10 more!
This is a perfectly adequate solution: but you'd probably want to use a switch, to simplify it even further:
$relative = $_GET['relative'];
switch ($relative) {
case 'mother':
return 'Harriet';
break;
case 'father':
return 'Robert';
break;
case 'daughter':
return 'Rachel';
break;
case 'grandmother':
return 'Audrey';
break;
default:
return 'relative not found!';
}
Great, this feels much more structured, but it's quite heavy on syntax, right? Perfectly serviceable, but let's take it one step further.
Enter lookup-arrays. A lookup array is a key-value paired list, where the key is what is looked up!
The above, in the form of a lookup-array is:
$relative = $_GET['relative'];
$relatives = [
'mother' => 'Harriet',
'father' => 'Robert',
'daughter' => 'Rachel',
'grandmother' => 'Audrey',
];
return $relatives[$relative] ?? 'relative not found!';
You can see how much easier to read a lookup-array is, and how it dramatically reduces the quantity of code, in a concise way! To note, lookup-arrays aren't always the best choice, but when they are, it should feel pretty natural!
Thanks for reading - let me know your thoughts!
Posted on February 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.