Home > Article > Backend Development > How to Convert a PHP Array into a Query String?
PHP Function to Construct a Query String from an Array
In PHP, there's an inherent function that effortlessly constructs a query string from an array of key-value pairs. This article aims to unveil the name of this elusive function.
Built-In PHP Function
Despite the abundance of third-party solutions available online, the PHP language offers its own dedicated function for this task. Its name is http_build_query().
Usage
The http_build_query() function accepts an array of key-value pairs as its input and returns a query string. The syntax is as follows:
<code class="php">http_build_query($data);</code>
where $data is the input array.
Example
Consider the following array:
<code class="php">$data = array( 'name' => 'John Doe', 'age' => 30, 'city' => 'New York' );</code>
Using http_build_query():
<code class="php">$queryString = http_build_query($data);</code>
The resulting query string will be:
name=John+Doe&age=30&city=New York
Notes
The above is the detailed content of How to Convert a PHP Array into a Query String?. For more information, please follow other related articles on the PHP Chinese website!