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!
Top comments (7)
Since PHP 8.0 you can use match expression.
I love the match expression. Such a shame that so many existing codebases are stuck with older versions PHP.
I'd always opt for Match in PHP 8 😊
I'd never heard of it. It looks better than switch for most things, but oh dear the syntax is horrid with those arrows. It makes it look like it should be an associative array.
BTW one key difference between match and switch is that match uses strict comparison whether switch doest not
You've made the
switch
version look more verbose by changingreturn
toecho
, meaning it's no longer the same code as in the first example. If you were refactoring the first, you'd do:That could do with a
default
, of course, but you know what I mean :)You're totally right! I should update that! Thanks for mentioning it :)
Great post! Thank you for sharing!