1

I have a query string. For example:

?filters=1,2,3,4

It gets turned into an array:

$filters = explode(',', $_GET['filters']);

You could push a new value on

$filters = array_push($filters, $new->filter);

Then turn it into the query string

http_build_query($filters);

Or, remove a value

$filters = array_diff($filters, [$new->filter]);

Then turn it into the query string

http_build_query($filters);

I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist. Alternative solutions are also welcome.

Thank you.

1
  • George, that is the attempt?! You would just simply test the array based on the functions I included. Commented Apr 21, 2014 at 19:23

3 Answers 3

3

Hopefully I'm understanding you correctly "I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist.". Also, not sure if it is elegant but may spark other ideas:

$filters = in_array($new->filter, $filters) ?
    array_diff($filters, [$new->filter]) :
    array_merge($filters, [$new->filter]);
Sign up to request clarification or add additional context in comments.

Comments

2

That's about as elegant as it gets, unless you want to use PHP's array notation "hack", e.g.

?filters[]=1&filters[]=2&filters[]=3&etc...
        ^^---

That'd save you the explode() stage and gives you the ability to treat $_GET['filters'] as an array directly, but at the cost of an uglier/longer URL.

Comments

0

Perhaps you should write 2 functions, "remove" and "add", which would each loop through the array looking for the value in question. Then the remove function could remove it, and the add function could add it. The functions themselves would not be so elegant, but using them would be simple elsewhere in your code.

Comments

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.