Home > Backend Development > PHP Tutorial > How Can I Parse a Query String into an Array in PHP?

How Can I Parse a Query String into an Array in PHP?

Patricia Arquette
Release: 2024-12-17 09:12:25
Original
267 people have browsed it

How Can I Parse a Query String into an Array in PHP?

Parsing Query Strings into Arrays

In the realm of web programming, it's often necessary to manipulate query strings – snippets of data appended to URLs. One common task is to parse these strings into structured arrays for easier handling.

Consider this query string:

pg_id=2&parent_id=2&document&video
Copy after login

Our goal is to convert this string into an array resembling:

array(
    'pg_id' => 2,
    'parent_id' => 2,
    'document' => ,
    'video' =>
)
Copy after login

The Solution: parse_str Function

PHP's parse_str function excels at this task. It takes two parameters: the query string to parse and an output array variable. By specifying the second parameter, we instruct the function to populate an array with retrieved key-value pairs.

Code Demonstration

$queryString = "pg_id=2&parent_id=2&document&video";
parse_str($queryString, $queryArray);

print_r($queryArray);
Copy after login

This code assigns the query string to the $queryString variable and invokes parse_str to populate the empty $queryArray with the parsed data. The resulting array can be displayed using print_r.

Output:

Array
(
    [pg_id] => 2
    [parent_id] => 2
    [document] =>
    [video] =>
)
Copy after login

Additional Notes

  • Keep in mind that parse_str differentiates between arrays and strings in query strings.
  • For example, if "document[]" appears in the query string, parse_str will interpret it as an array in the output.
  • By setting the second parameter to true, parse_str treats all values as strings instead of automatically coercing them to their appropriate types.

The above is the detailed content of How Can I Parse a Query String into an Array 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template