简体   繁体   中英

stristr php function doesn't work as it should

for($check = 0; $check<12;$check++)
{
    echo "<strong>" .$cars[$check] .":</strong>";

    foreach($models as $model)
    {

        if ( stristr($model, $cars[$check]))

        {
            echo $model;
        }
    }

}

$cars is an array that contains 12 vehicle makes, $models is a large array (about 3000 elements) which contains many models of different car makes. I expect from my code to echo the model name if it can find the name of the car ($cars[$check]) in it. The problem is that it returns nothing, but if I replace the "$cars[$check]" in the if function with a static string like "BMW", then it has no problem in returning the models that contain the string "BMW". I tried everything for hours and searched the internet in and out and couldn't find a solution. Is it something wrong with the code, or have approached this in a wrong way?

You could try using foreach for the cars model as well, and use a key instead of $check : You keep a natural association with the key and value doing this so you can't break it by having $check being an undefined index (and killing your PHP execution in some instances)

foreach($cars as $check => $car) {

    echo "<strong>" . $car . "</strong>";
    foreach($models as $model) {
        if(stristr($model, $car))
            echo $model;
    }

}

--edit-- if you are only expecting one model to be assigned to each car, and you have lots of models, you should cut down your server processing by using continue after your echo $model . This will skip the iteration of the car's foreach loop and move on to the next.

if(stristr($model, car)) {
    echo $model;
    continue 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM