Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.
The `http_build_query()` function in PHP is used to generate a URL-encoded query string from an associative (or indexed) array. It’s commonly used when you need to construct a query string to be appended to a URL in HTTP requests. This function is particularly useful when dealing with forms and constructing URLs with dynamic parameters.
Here’s an example of how you can use `http_build_query()`:
<?php // Sample associative array with query parameters $data = array( 'name' => 'John Doe', 'age' => 30, 'city' => 'New York', 'country' => 'USA' ); // Generate a URL-encoded query string $queryString = http_build_query($data); // Output the generated query string echo $queryString; ?>
Output:
name=John+Doe&age=30&city=New+York&country=USA
In this example, the associative array `$data` contains key-value pairs representing various parameters. When `http_build_query()` is called with this array, it constructs a URL-encoded query string where each key-value pair is separated by an ampersand (`&`), and the key and value are separated by an equals sign (`=`). Additionally, spaces are replaced by plus signs (`+`) in the resulting string.