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

How to Parse a Query String into an Array in PHP?

Susan Sarandon
Release: 2025-01-01 12:12:11
Original
393 people have browsed it

How to Parse a Query String into an Array in PHP?

Parse Query String into an Array

When attempting to convert a string into an array, it's essential to understand the process and utilize the appropriate functions. In this particular case, the challenge is to transform a query string into an array format.

To achieve this, PHP offers the parse_str function. This function accepts a query string as its first parameter, and it converts the string into an array. However, by default, parse_str assigns the parsed data to individual variables. To store the data in an array instead, an additional second parameter must be added. This parameter should be an empty array, as seen below:

$queryString = "pg_id=2&parent_id=2&document&video";

parse_str($queryString, $queryArray);

print_r($queryArray);
Copy after login

This code will transform the query string into an array called $queryArray, with each pair of key-value data from the query string stored as an element in the array. The output of print_r($queryArray) will be:

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

The above is the detailed content of How to 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