Backend Development 4 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's http_build_query() to Build URL Query Strings

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.

BackendWeb DevelopmentPHPURLhttp_build_query
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.