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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Decomposing a URL with parse_url and rebuilding it part by part lets you change one piece without corrupting the rest.
- 2array_merge gives new params precedence over existing ones, making override behaviour predictable.
- 3Returning null instead of a malformed string forces callers to handle the no-host case explicitly.
Related explainers
go
package main import ( "errors"
Parsing and validating CLI flags in Go
cli-parsing
validation
error-handling
Intermediate
8 steps
javascript
'use server' import { revalidatePath } from 'next/cache' import { redirect } from 'next/navigation'
How a Next.js Server Action updates a post
server-actions
authorization
validation
Intermediate
7 steps
php
<?php namespace App\Support;
Locale-aware formatting with PHP's intl extension
internationalization
encapsulation
constructor-injection
Intermediate
7 steps
php
<?php class ImageUploadService {
Validating file uploads safely in PHP
file-upload
input-validation
security
Intermediate
8 steps
php
<?php namespace App\View;
Building a safe HTML escaper in PHP
security
xss
escaping
Intermediate
6 steps
javascript
const transitions = { cart: { checkout: 'shipping' }, shipping: { submitAddress: 'payment', back: 'cart' }, payment: { submitPayment: 'review', back: 'shipping' },
A finite state machine for checkout flow
state-machine
event-driven
data-driven-design
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/merging-query-params-onto-a-url-in-php-explained-php-e5ee/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.