Home  >  Article  >  Backend Development  >  How to Convert a PHP Array into a Query String?

How to Convert a PHP Array into a Query String?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 19:04:02640browse

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 key-value pairs are separated by ampersands (&).
  • Spaces in the values are automatically URL-encoded.
  • The function can also handle nested arrays, allowing for complex query strings to be built.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn