Search code examples
phpconditional-statementslogic

How Do I Parse An 8-Part Classifier Code?


I have a classifier that looks like "1-3--6--". If it contains a "1" I'd like to print "a" and if it contains "2" I'd like to print "b". If it contains a "1" and "2" then I'd want to print "a, b".

I'm aware of str_contains and can do an easy check for a number:

if (str_contains($check, 1)) { 
              echo 'a'; } 
            else { echo 'no'; }

but what to do in the case of a "1" and a "3" on order not to have a check for every single combination of the 8 numbers?


Solution

  • Make an array of the codes for each match in a loop.

    $matches = [];
    for ($i = 1; $i <= 9; $i++) {
        if (str_contains($check, $i)) {
            $matches[] = chr(ord("a") + $i-1);
        }
    }
    if (empty($matches)) {
        echo "no";
    } else {
        echo implode(',', $matches);
    }