php 39 lines · 8 steps

Merging query params onto a URL in PHP

A small utility that safely adds or overrides query parameters on a URL while preserving every other part.

Explained by highlit
1<?php
2 
3namespace App\Support;
4 
5final class UrlBuilder
6{
7 public static function withParams(string $url, array $params): string
8 {
9 $parts = parse_url($url);
10 
11 if ($parts === false) {
12 throw new \InvalidArgumentException("Malformed URL: {$url}");
13 }
14 
15 parse_str($parts['query'] ?? '', $existing);
16 $merged = array_merge($existing, $params);
17 
18 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
19 $user = $parts['user'] ?? '';
20 $pass = isset($parts['pass']) ? ':' . $parts['pass'] : '';
21 $auth = $user !== '' ? $user . $pass . '@' : '';
22 $host = $parts['host'] ?? '';
23 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
24 $path = $parts['path'] ?? '';
25 $query = $merged ? '?' . http_build_query($merged, '', '&', PHP_QUERY_RFC3986) : '';
26 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
27 
28 return $scheme . $auth . $host . $port . $path . $query . $fragment;
29 }
30 
31 public static function host(string $url): ?string
32 {
33 $host = parse_url($url, PHP_URL_HOST);
34 
35 return $host !== null && $host !== false
36 ? strtolower(preg_replace('/^www\./', '', $host))
37 : null;
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Decomposing a URL with parse_url and rebuilding it part by part lets you change one piece without corrupting the rest.
  2. 2array_merge gives new params precedence over existing ones, making override behaviour predictable.
  3. 3Returning null instead of a malformed string forces callers to handle the no-host case explicitly.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Merging query params onto a URL in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code