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

How to Convert a PHP Array into a Query String?

Mary-Kate Olsen
Release: 2024-11-02 19:04:02
Original
736 people have browsed it

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>
Copy after login

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>
Copy after login

Using http_build_query():

<code class="php">$queryString = http_build_query($data);</code>
Copy after login

The resulting query string will be:

name=John+Doe&age=30&city=New York
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template