MeshWorld India LogoMeshWorld.
PHPTutorial1 min read

How to build query string from an array with http_build_query in PHP

Vishnu
By Vishnu
|Updated: Jun 22, 2026
How to build query string from an array with http_build_query in PHP

PHP has built in function http_build_query that can be used to prepare a query string from an array.

Instead of explicitly appending elements to string, this function comes handy, which takes cares of generating URL-encoded query string either from an associative or indexed array.

Also it works with an object, comprising of public properties only into final query string.

Supported in PHP >= 5

Example 1

$data = [
  'search' => 'cars',
  'sourceType' => 'image',
];

echo http_build_query($data);

/*
 * Output
 *
 * "search=cars&sourceType=image"
*/

Example 2

$data = [
    'firstName' => 'Shirley',
    'lastName' => 'Setia',
    'profession' => 'Singer',
    'location' => [
        'city' => 'Daman',
        'state' => 'Gujarat',
        'country' => 'India',
    ],
];

echo http_build_query($data);

/*
 * Output
 *
 * "firstName=Shirley&lastName=Setia&profession=Singer&location%5Bcity%5D=Daman&location%5Bstate%5D=Gujarat&location%5Bcountry%5D=India"
*/

Hope you find it useful.

Happy coding

Share_This Twitter / X
Vishnu
Written By

Vishnu

Founder & Principal Architect at MeshWorld. Senior engineer and instructor specializing in AI agent systems, scalable web architecture, and modern development workflows.

Enjoyed this article?

Support MeshWorld and help us create more technical content