Using PHP's http_build_query() to Build URL Query Strings
This article explains how PHP's http_build_query() function converts associative arrays or objects into properly encoded URL query strings, covering basic usage, handling of multidimensional arrays, objects, and special characters with clear code examples.
In PHP development, constructing URL query strings from parameters is a common task. The built‑in http_build_query() function simplifies this by converting an associative array or object into a URL‑encoded query string, joining key‑value pairs with "&".
Basic Example
<?php
$params = [
'name' => 'John',
'age' => 25,
'city' => 'New York'
];
$queryString = http_build_query($params);
echo $queryString;
?>The output is name=John&age=25&city=New+York .
Multidimensional Arrays
<?php
$params = [
'name' => 'John',
'age' => 25,
'city' => 'New York',
'hobbies' => [
'reading',
'swimming',
'traveling'
]
];
$queryString = http_build_query($params);
echo $queryString;
?>The resulting string encodes each hobby as separate parameters, e.g., hobbies=reading&hobbies[1]=swimming&hobbies[2]=traveling .
Objects
<?php
class Person {
public $name = 'John';
public $age = 25;
public $city = 'New York';
}
$person = new Person();
$queryString = http_build_query($person);
echo $queryString;
?>The object’s public properties are converted to name=John&age=25&city=New+York .
Special Characters
<?php
$params = [
'name' => 'John Doe',
'age' => 25,
'city' => 'New York'
];
$queryString = http_build_query($params);
echo $queryString;
?>Spaces are URL‑encoded as plus signs, producing name=John+Doe&age=25&city=New+York .
Summary
The http_build_query() function is a versatile tool for PHP developers, handling simple lists, nested arrays, objects, and special characters, thereby streamlining the creation of URL‑compatible query strings and improving code readability and maintainability.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.