Home > Backend Development > PHP Tutorial > How do I Convert an Array to a Query String in PHP?

How do I Convert an Array to a Query String in PHP?

DDD
Release: 2024-10-30 03:58:28
Original
922 people have browsed it

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

Additional Parameters

The http_build_query() function also accepts several optional parameters:

  • encoding: The character encoding to use (default: RFC 1738)
  • numeric_prefix: Prefix to use for numeric array indices (default: none)
  • arg_separator: Value separator used for array values (default: &)

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template