lundi 18 septembre 2017

PHP - Is there a better way to search a large string than with multiple IFs

I have a variable called $data that is storing a large amount of data. I know that data will contain ONE of these words… cheese, crackers, or fruit. Or, it could possibly contain none of those words. Right now, I do this….

if (strpos($data,"cheese")!==false) $food="cheese";
else if (strpos($data,"crackers")!==false) $food="crackers";
else if (strpos($data,"fruit")!==false) $food="fruit";
else $food=”none”;

So, if cheese is found, the data is only being searched once. If cheese isn’t found, the data is being searched again, because it first looked for cheese, didn't find it, then had to search again to look for crackers. See the problem? So, if no food is found, the data ends up being searched 3 times before the food variable is finally set (am I right, is that how it works?).

I’m wondering if there’s a more efficient way to search. I thought of a possible way, but I don’t know how to do it… What if I searched for all three foods at once like this…

if (strpos($data,"cheese")!==false or
strpos($data,"crackers")!==false or
strpos($data,"fruit")!==false)
$food=THE WORD THAT WAS FOUND GOES HERE

I want to be able to set the food variable to what was found. If this is possible, Am I correct in thinking this would be much faster because you’re searching the data only once? Or is PHP still searching 3 times to look for each item? And is it even possible to set the food variable to what was found?

Aucun commentaire:

Enregistrer un commentaire