penpen
penpen

Reputation: 935

Building query strings in PHP

I'm wondering if there is a technique or function to do this or if I'm just going to have to have a ton of IF statements/arrays here-

I have a page called products.php and a few different filters I add in the query string. All the filters (if chosen) could look like this:

products.php?cat=chairs&type=pine&search=Vienna+Range

Is there a simple way to build the query for use again?

I'm going to have buttons/a search box to change the filters I'm using, so will I have to build the URL and query up again for each filter?

For example I'd like to have:

<a href="products.php?cat=tables">Tables</a>
<a href="products.php?cat=beds">Beds</a>
<a href="products.php?cat=chairs">Chairs</a>

but also build the query so that it remembers my search term, wood type and range; so clicking on "Tables" would take me to

products.php?cat=chairs&type=pine&search=Vienna+Range.

Upvotes: 2

Views: 1167

Answers (1)

Alessandro Desantis
Alessandro Desantis

Reputation: 14343

You can write something like:

<?php
$params = array(
    'cat'    => 'chair',
    'type'   => 'pine',
    'search' => 'Vienna Range',
);

print_r(http_build_query($params) . PHP_EOL);

You'll get this:

cat=chair&type=pine&search=Vienna+Range

Upvotes: 3

Related Questions