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
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 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.