eozzy
eozzy

Reputation: 68680

Check if string starts with in array values

I have an array of excluded category IDs. I'm trying to fetch data from the DB and filter products based on this array.

So if level 1 is excluded, products of level 2 and 3 are automatically excluded. Currently I'm doing this:

$excludedCategories = ['1000', '100011'];

while ($row = $result->fetch_assoc()) {
    $category = "1". $row['category'] . $row['sub_category'] . $row['category_id'];
    foreach ($excludeCategories as $exCategory) {
        if( substr($category, 0, strlen($exCategory)) === $exCategory ) {
            echo 'Category'. $category . " matches " . $exCategory . "<br>";
            continue;
        }
    }
}

.. but is there a better way of doing it without running the second loop?

Upvotes: 5

Views: 4202

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 98921

If you implode $excludedCategories to make a pattern for preg_match, you don't need the loop.

$excludedCategories = ['1000', '100011'];
while ($row = $result->fetch_assoc()) {
    $category = "1". $row['category'] . $row['sub_category'] . $row['category_id'];
        if( preg_match("/^".implode("|",$excludedCategories)."/", $category)) {
            echo "Category: $category Excluded <br>";
     }
}

Upvotes: 8

Related Questions