Indexing an array
Learning about PHP's obscure array_column function.
Pherlock Homels suspects that Poriarty has managed to join the list of Zend Certified Engineers. Phatson, as diligent as ever, has obtained a list of all the engineers, but there is a problem: the list is not indexed, making searches slower. Will Pherlock and Phatson be able to index it efficiently? Let's see.
Example list
For security reasons, as you can imagine, Pherlock could only give me a fictitious list, but it will illustrate the solution:
[
[
'name' => 'Carlos Rodriguez',
'dob' => '1954/02/18',
'code' => 'ZEN123423434',
],
[
'name' => 'John Doe',
'dob' => '1998/11/23',
'code' => 'ZEN123423435',
],
[
'name' => 'Mike Altuve',
'dob' => '1994/08/05',
'code' => 'ZEN123423436',
],
]
Initial solution
Phatson quickly began writing code and found a solution that does solve the problem. Let's take a look:
$indexedArray = [];
foreach ($certifiedEngineers as $certifiedEngineer) {
$indexedArray[$certifiedEngineer['code']] = $certifiedEngineer;
}
This is a correct solution, but Pherlock knows that Poriarty likes shorter, more cryptic code. He took this opportunity to deepen his knowledge of PHP array functions.
Final solution
After a long search, Pherlock found a function that indexes an array by any given column in a single line: array_column!
This is the sort of function and code Poriarty likes to use in his scripts. It tends to confuse less trained minds because the function's name and what it can achieve are somewhat different. Let's see the code:
$indexedArray = array_column($certifiedEngineers, null, 'code');
As its name suggests, the function's primary purpose is to extract values from the column specified by its second argument. But if that argument is null, it returns the entire array indexed by the column specified by the third argument. Confused? So was I when I first saw the code.
Your solution
What did you think of Pherlock's solution? Did you already know it? Does Poriarty have another array-indexing trick up his sleeve that Pherlock has missed? Let us know with a tweet to #webcu.