How to Convert Query String to an Array in PHP?
Last Updated :
20 Aug, 2024
In this article, we will see how to convert a query string to an array in PHP. The Query String is the part of the URL that starts after the question mark(?).
Examples:
Input: str = "company=GeeksforGeeks&address=Noida&mobile=9876543210"
Output: Array (
[company] => GeeksforGeeks
[address] => noida
[mobile] => 9876543210
)
Input: str = "name=xyz&language=english&age=23&education=btech"
Output: Array(
[name] => xyz
[language] => english
[age] => 23
[education] => btech
)
Below are the methods to convert a query string to an array:
Using parse_str() Function
The parse_str() function parses a query string into variables. The string passed to this function for parsing is in the format of a query string passed via a URL.
Syntax:
void parse_str($string, $array)
Example 1: This example uses parse_str() function to convert the query string into the array variable.
PHP
<?php
// Query String
$query = "name=xyz&address=noida&mobile=9876543210";
// Parses a query string into variables
parse_str($query, $res);
// Print the result
print_r($res);
?>
OutputArray
(
[name] => xyz
[address] => noida
[mobile] => 9876543210
)
Example 2: This example uses parse_str() function to convert the query string into the array and store into $arr variable.
Using $_GET Method
The GET method sent the data as URL parameters that are usually strings of name and value pairs separated by ampersands (&). We can display the get data using print_r() function.
Example: This example uses $_GET method to convert the query string to the array.
PHP
<?php
if (!empty($_GET)) {
print_r($_GET);
}
else {
echo "No GET data passed!";
}
?>
Output:

Using explode() and Custom Parsing
For a manual approach, you can use explode() to split the query string and then parse it.
Example: Manually parsing the query string using explode().
PHP
<?php
// Query String
$query = "name=xyz&address=noida&mobile=9876543210";
// Split the query string into key-value pairs
$pairs = explode('&', $query);
// Initialize an empty array
$result = array();
// Loop through each pair
foreach ($pairs as $pair) {
// Split the pair into key and value
list($key, $value) = explode('=', $pair);
// Add the key-value pair to the result array
$result[$key] = $value;
}
print_r($result);
?>
Output:
Array
(
[name] => xyz
[address] => noida
[mobile] => 9876543210
)
Using http_build_query and parse_url
This PHP method converts a query string to an array using parse_url to extract query parameters and parse_str to convert them into an associative array.
Example: This example shows the implementation of the above-mentioned approach.
PHP
<?php
function queryStringToArray($queryString) {
// Parse the query string into its components
$parsedUrl = parse_url('?' . $queryString);
// Use parse_str to convert query string into an associative array
$resultArray = [];
if (isset($parsedUrl['query'])) {
parse_str($parsedUrl['query'], $resultArray);
}
return $resultArray;
}
// Example usage
$queryString = "name=Geek&age=25&city=Noida";
$resultArray = queryStringToArray($queryString);
print_r($resultArray);
?>
OutputArray
(
[name] => Geek
[age] => 25
[city] => Noida
)
Using json_decode() with json_encode()
Another interesting approach to convert a query string to an array is by converting the query string to JSON format first and then decoding it into an associative array using json_decode().
Example: This approach adds another layer of versatility to the task of converting a query string into an associative array in PHP, utilizing JSON encoding and decoding for accurate and efficient conversion.
PHP
<?php
function queryStringToArray($queryString)
{
// Convert query string to JSON format
$json = json_encode(
array_reduce(
explode("&", $queryString),
function ($result, $item) {
list($key, $value) = explode("=", $item);
$result[$key] = urldecode($value);
return $result;
},
[]
)
);
// Decode JSON to associative array
$array = json_decode($json, true);
return $array;
}
$queryString1 = "company=GeeksforGeeks&Address=Noida&Phone=9876543210";
print_r(queryStringToArray($queryString1));
?>
OutputArray
(
[company] => GeeksforGeeks
[Address] => Noida
[Phone] => 9876543210
)
Using preg_match_all and Regular Expressions
This approach uses regular expressions with preg_match_all to match all key-value pairs in the query string and then parse them into an associative array.
Example: This example demonstrates how to convert a query string to an array using preg_match_all:
PHP
<?php
// Example query string
$queryString = "name=xyz&language=english&age=23&education=btech";
// Initialize an array to store matches
$result = [];
// Use regular expression to match key-value pairs
preg_match_all('/([^&=]+)=([^&]*)/', $queryString, $matches);
// Loop through the matches and populate the result array
for ($i = 0; $i < count($matches[1]); $i++) {
$key = urldecode($matches[1][$i]);
$value = urldecode($matches[2][$i]);
$result[$key] = $value;
}
print_r($result);
?>
OutputArray
(
[name] => xyz
[language] => english
[age] => 23
[education] => btech
)
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line providing more flexibility. HTML adds Structure to a web page, CSS st
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook created React. Developers with a Javascript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. It is essential for both front-end and back-end developers to have a strong command of
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable. Applications are built using reusable compo
8 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
10 min read
REST API Introduction
REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
Half Wave Rectifier
A Half-wave rectifier is an electronic device that is used to convert Alternating current (AC) to Direct current (DC). A half-wave rectifier allows either a positive or negative half-cycle of AC to pass and blocks the other half-cycle. Half-wave rectifier selectively allows only one half-cycle of th
15 min read