Home > Article > Backend Development > How do I Convert an Array to a Query String in PHP?
PHP Function for Building Query Strings from Array
PHP provides a built-in function for easily converting an array of key-value pairs into a query string. The function's name is http_build_query().
How to Use http_build_query()
The http_build_query() function takes an array as an argument and returns a string containing the formatted query string. The key-value pairs in the array are encoded as name-value pairs, separated by an equals sign and ampersand (&).
Here's an example:
<code class="php">$data = array( 'name' => 'John Doe', 'age' => 30, 'gender' => 'male' ); $query_string = http_build_query($data); echo $query_string; // Outputs: name=John+Doe&age=30&gender=male</code>
Additional Parameters
The http_build_query() function also accepts several optional parameters:
Note:
The http_build_query() function is typically used to create query strings for HTTP requests. However, it can also be useful for other scenarios where you need to convert an array into a formatted string.
The above is the detailed content of How do I Convert an Array to a Query String in PHP?. For more information, please follow other related articles on the PHP Chinese website!