1

On my website I have a list of news available at /news/ which displays all news. I allow news to be filtered based on subject by adding categories to the URL like: /news/sports or multiple categories /news/sports+politics+crime

Within my application I explode the URL on the + and build an array which I use to grab the correct news items. In addition to grabbing the items, I also print "Tags" onto the page, with an "X" to remove the given category. So if you went to /news/sports+politics+crime then above the list of News I have printed Sports[X] Politics[X] Crime[X]

What I want to do, is like the [X] to the same URL MINUS the category that is being removed. So the href tag of the crime [X] would be /news/sports+politics but the href tag of sports would be /news/politics+crime

What is the best way to do this?

While generating the page I am looping thru my array of categories like so:

foreach ($category as $cat) {
    echo $cat . '<a href="/news/">[X]</a>';
}

What is the best way to print the link without the category being removed? I was thinking I could somehow flatten the array into a plain old string, and find/replace the given item ex +crime and then turn that back into a URL. Any ideas?

1 Answer 1

3

You can use array_diff() to remove the current category from the $category array:

foreach ($category as $cat) {
  $other_categories = array_diff($category, array($cat));
  echo $cat . ' <a href="/news/' . implode('+', $other_categories) . '">[X]</a>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Holy cow, that works perfectly. That is much easier than I had expected. Than you so much for the help

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.