Reputation: 17
I wonder if there is a "simple" PHP solution to create multiple URL parameters. Until now I am able to create a "one click" filter like this:
$url_param = ($_GET["sort"]);
<a href="?sort=rank-chipset">Sort by this</a>
and then:
if($url_param == 'rank-chipset') {do this}
This works great as a "one click" URL parameter for filtering! I like this simple solution to do things with URL parameters, but can't figure out how to do something similar so i can give the option to users to select multiple parameters, like brand1, brand2, year 2021 and more.
I would prefer this to work like this: If users clicks brand1 filter then instantly reload page and show brand1 products, after if also clicks brand2 then show also brand1 and brand2 products. If users clicks again brand1 remove brand1 from filtering.
Upvotes: 0
Views: 1053
Reputation: 47894
If you are going to design a solution that writes the navigation history directly in the url, then set up the storage with the goal of easy/swift data mutation.
Code: (untested)
function toggleItem($item, $cache) {
$cache[$item] = isset($cache[$item]) ? null : 1;
return $cache;
}
// show array_keys($_GET) as you wish
$allItems = ['a', 'b', 'c', 'd'];
foreach ($allItems as $item) {
printf(
'<a href="?%s">%s</a>',
http_build_query(toggleItem($item, $_GET)),
$item
);
}
The advantage in this is that the values are always stored as array keys. This means checking for their existence is optimized for speed and http_build_query()
will ensure that a valid querystring is generated.
A special (perhaps unexpected for the unknowing developer) behavior of http_build_query()
ensures that an element with a null
value will be stripped from its output (the key will not be represented at all). This acts as if unset()
was used on the array.
If you want keep these item values in a specific subarray of $_GET
, you can adjust the snippet for that too. You would set this up with $_GET['nav'] ?? []
and access array_keys($_GET['nav'] ?? [])
. One caveat to this performance boost is that PHP's array keys may not be floats -- they get automatically converted to integers. (I don't know the variability of your items.)
Upvotes: 1
Reputation: 781059
Make the filter
parameter a comma-delimited list of filters. Then combine the existing value of $_GET['filter']
with the filter for that link.
function add_or_remove_filter($new, $filters) {
$pos = array_search($new, $filters);
if ($pos === false) {
// add if not found
$filters[] = $new;
} else {
/remove if found
unset($filters[$pos]);
}
return implode(',', $filters);
}
$filters = explode(',', $_GET['filter'] ?? '');
?>
<a href="?filter=<?php echo add_or_remove_filter("brand1", $filters); ?>">Brand 1</a>
<a href="?filter=<?php echo add_or_remove_filter("brand2", $filters); ?>">Brand 2</a>
<a href="?filter=<?php echo add_or_remove_filter("2021", $filters); ?>">Year 2021</a>
Upvotes: 3