Viagra online
XANAXadderall onlineLevitraPuppies for sale


Merge query string

Ever have a url like this…

index.php?dosearch=true&page=1&search[co_name]=best+buy&search[address1]=12+main+st&search[city]=bridgeport&search[state_province_abbrev]=ct

…and wanted to create a link that would go to page=2, but keep the rest of the query string?

This recently happened to me so I created a function. Normally this would be a trivial call to array_merge, but I needed it to handle single-level arrays too.

I present to you mergeQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function mergeQuery( $link ) {
 
	parse_str( $_SERVER['QUERY_STRING'], $qry );
	parse_str( $link, $lnk );
	$mergedQry = array_merge( $qry, $lnk );
 
	foreach( $mergedQry as $var => &$val ) {
 
		if ( is_array( $val ) ) {
			foreach ( $val as $val_k => $val_v ) {
				$finalQry .= sprintf( '%s[%s]=%s&', $var, $val_k, $val_v );
			}
		}
		else {
			$finalQry .= sprintf( '%s=%s&', $var, $val );
		}
 
	}
 
	return '?' . rtrim( $finalQry, '&' );
 
}

Any variables you supply will overwrite variables from the current query string.

Examples

<a href="<?= mergeQuery( 'page=1&id=23' ) ?>">
<a href="otherpage.php<?= mergeQuery( "page=5&id={$data['id']}" ) ?>">

Maybe someone else will find some use for it

Leave a Reply

You must be logged in to post a comment.