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
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
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.