5

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

  • 1000 is an example of Category Level 1 ID
  • 1000001 is an example of Category Level 2 ID
  • 1000001021 is an example of Category Level 3 ID

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?

6
  • may in in_array($category, $excludedCategories)? Commented May 13, 2016 at 23:22
  • preg_match can be used to solve it pretty easy if the array values can be converted to regex pattern if not Commented May 13, 2016 at 23:24
  • @manix Probably not because i need to check IDs that "start with" Commented May 13, 2016 at 23:28
  • I see. You are right Commented May 13, 2016 at 23:31
  • @3zzy Why do you need to loop the excludedCategories if the first start with 1000? I guess the second is automatically excluded, Am I getting this wrong? Commented May 13, 2016 at 23:43

1 Answer 1

8

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>";
     }
}
Sign up to request clarification or add additional context in comments.

1 Comment

In this case it is not a concern, but consider using preg_quote on all items of the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.