Reputation: 1649
I am creating a contact form, which needs to change the sendto address based on an entered postal code.
I have an array of postal codes which I can search through, so that I know if the postal code entered is actually in the array.
Here's how I search through the array:
$districts = [
'district' => [
[
'name' => 'District A',
'email' => '[email protected]',
'url' => 'district-a',
'postalcodes' => [
'3311AA',
'3311AB',
],
],
[
'name' => 'District B',
'email' => '[email protected]',
'url' => 'district-b',
'postalcodes' => [
'3317EA',
'3317EB',
'3317EC',
],
],
],
];
$results = array_filter($districts['district'], function($district) {
$key = array_search('3311AB', $district['postalcodes']);
return $key;
});
var_dump($results);
Now I need to return the email address, based on in which district the postal code is found.
How would I search for, for example, postal code 3311AB
and return the email address of the district to which it belongs?
Upvotes: 2
Views: 71
Reputation: 47764
From PHP8.4, you can enjoy functional style programming with the efficiency boost of short-circuiting internal loops by nesting array_any()
calls inside of an array_find()
call. Demo
$find = '3311AB';
echo array_find(
$districts['district'],
fn($d) => array_any(
$d['postalcodes'],
fn($pc) => $pc === $find
)
)['email'] ?? 'Not found';
// [email protected]
If limited by your PHP version or if a functional style script is not desired, a manual loop with a conditionally break performs the same way. I am implementing array destructuring syntax in the head of the loop to access only the relevant column values. Demo
$found = null;
$find = '3311AB';
foreach ($districts['district'] as ['email' => $e, 'postalcodes' => $pc]) {
if (in_array($find, $pc)) {
$found = $e;
break;
}
}
echo $found ?? 'Not found';
// [email protected]
Upvotes: 0