Skip to content
Advertisement

Best way to use multiple URL paramemetrs for advacned filtering with PHP?

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement