The goal of this task in terms of efficiency is to perform the array search with a minimum number of iterations and to guarantee that the array is never possibly iterated more that one full time (that's a big O of n
).
Any answers on this page that are preparing the data with array_column()
(or a classic loop) before even beginning the search have already disqualified itself from being an efficient technique.
The most performant technique will be to iterate the array with the intention of using an early break
. array_search()
uses an early break under the hood, but unfortunately it needs the data structure to be adjusted first.
Using any functional iterators will not afford the use of an early break, so they can be discounted as well.
This is one time when a classic loop is most appropriate. With the conditional break, the snippet never iterates more than necessary to find the match.
Code: (Demo)
$array = [
['email' => 'a@a.com', 'name' => 'a'],
['email' => 'b@b.com', 'name' => 'b'],
];
$needle = 'a@a.com';
$name = null;
foreach ($array as $row) {
if ($row['email'] === $needle) {
$name = $row['name'];
break;
}
}
var_export($name);
Output:
'a'