How can you implement a partial search feature for city names based on postal codes in PHP using arrays or databases?
To implement a partial search feature for city names based on postal codes in PHP, you can create an array or database table mapping postal codes to city names. You can then use a search function to match partial postal codes and return corresponding city names. This can be achieved by iterating through the postal code data and checking if the input matches any partial postal codes.
// Sample array mapping postal codes to city names
$postalCodes = [
'10001' => 'New York',
'20001' => 'Washington D.C.',
'30001' => 'Atlanta',
// Add more postal code mappings as needed
];
function searchCityByPostalCode($partialPostalCode, $postalCodes) {
$matches = [];
foreach ($postalCodes as $postalCode => $city) {
if (strpos($postalCode, $partialPostalCode) !== false) {
$matches[$postalCode] = $city;
}
}
return $matches;
}
// Example usage
$partialPostalCode = '10';
$results = searchCityByPostalCode($partialPostalCode, $postalCodes);
foreach ($results as $postalCode => $city) {
echo "City: $city, Postal Code: $postalCode\n";
}
Keywords
Related Questions
- Are there any potential pitfalls to be aware of when using the unset function to remove elements from an array in PHP?
- Why is it recommended to use a hidden field instead of adding a second variable to the select field in the PHP script?
- What is the best practice for repeating a string multiple times in PHP?