Search code examples
phpstringcomparison

check if string exists within two lists of strings (separated by commas)


I want to check if a given 2-character value (my input: $string), exists inside any of my two separate lists, of possible matching values:

One list is dynamic (it will be read from my DB), and the values in it are separated by commas, with space after each comma:

It can be for example:

$dynamic_list="AA, AB, BA"
$dynamic_list="BC"
$dynamic_list="" (Empty)

The second list is a static list that I will maintain myself, and should be within the script itself.

I’m not sure how to build it. Maybe just define a variable like:

$static_list="MC,JL,EO";

If the string matches any of the strings in any of those lists, I just want to output that string, otherwise output "no match".

What is the best and fast way to do this?


Solution

  • Concatenate the two strings with the same delimiter that the strings use, and check as normal.

    Performing aditional string or array manipulations are needless overhead.

    Code: (Demo)

    $dynamic_list = "AA, AB, BA";
    $static_list = "MC,JL,EO";
    
    $search = "JL";
    
    if (strpos($dynamic_list . ',' . $static_list, $search) !== false) {
        echo 'found';
    } else {
        echo 'not found';
    }
    

    But, really, you should check the static string first. Then only bother making a trip to the database IF you don't have a match in the static string.

    As for querying, you might count the number of rows where the search string is found by LOCATE() -- since you don't need the data, just confirmation of a match.