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

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳