0

So i have these two strings:

$title = 'Chair Material Suede Black';

$title = 'Chair Material Suede Red';

This is a snippet from my PHP function:

elseif (stripos($title, 'Suede') !== false) {
    if (stripos($title, 'Red') !== false) {
        return 'Red Suede Chair';
    }
    else {return "TEMP_Category";}
}

The function continues, and 50 lines down there is this code:

elseif (stripos($title, 'Suede') !== false) {
        if (stripos($title, 'Black') !== false) {
            return 'Black Suede Chair';
        }
        else {return "TEMP_Category";}
    }

However, the string 'Chair Material Suede Black' ALWAYS returns 'TEMP_Category', because the search for 'Red' and 'Suede' is done prior to the Black one.

Is there any way to let it pass to the 'black' search?

MantiNL
  • 69
  • 12

2 Answers2

3

Combine the two checks:

elseif (stripos($title, 'Suede') !== false && stripos($title, 'Red') !== false) {

And move the else with TEMP_Category to the end of the checks.

elseif (stripos($title, 'Suede') !== false && stripos($title, 'Red') !== false) {
    return 'Red Suede Chair';
} elseif (stripos($title, 'Suede') !== false && stripos($title, 'Black') !== false) {
    return 'Black Suede Chair';
} else {
    return "TEMP_Category";
}
Fenton
  • 241,084
  • 71
  • 387
  • 401
0

However, the string 'Chair Material Suede Black' ALWAYS returns 'TEMP_Category', because the search for 'Red' and 'Suede' is done prior to the Black one.

Just for clarity that's simply because you're using elseif (stripos($title, 'Suede') !== false). So you will never reach the second (btw. identical) condition. PHP will skip every other elseif after a first matching condition. And because the first one will return "TEMP_Category" (because it's not Red) you get the wrong result.

Accept the answer from @Fenton because it's how you can solve it ;-)

Michael Hirschler
  • 2,345
  • 16
  • 28