I'm trying to write a PHP function to loop into a multidimensional array to match it with a business name then return to me the "business type".
With my current skills, I wrote this function but I would like to know if there's a better solution other than looping twice because my real arrays are much bigger than the example below.
Note: I'm a student, I already searched StackOverflow but couldn't find my need.
function find_business_type($dealer_name) {
$business_type = [
"OEM" => ["kia", "mercedes"],
"Rent" => ["rent", "rent-a-car"],
"Workshop" => ["shop", "workshop"],
"Spare Parts" => ["spare", "parts", "part"],
"General Trading" => ["gen", "general"]
];
foreach ($business_type as $key => $values) {
foreach ($values as $value) {
if (strpos($dealer_name, $value) !== false) {
return $key;
}
}
}
}
$my_dealer = "super-stars-123 rent a car";
echo find_business_type($my_dealer);
Output: "Rent"
mercedes rent a car. your function will return "OEM" because it is the first match. But what about "Rent"? it would also have matched. That is why jeroen suggests returning an array that contains "OEM" and "Rent"$business_typeinto some structure that can be searched faster. And there are many ways to do that but in the end it cost more performance to do that if you have to do it with every search process, so you have to cache it or use a special data base depending on the size of your data and how often it changes it might not be worth so much effort. Because it will get far more complicated. Still I suggest asking the question on Code Review. :)