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
How to Convert Array to String in PHP?
We are given an array and the task is to convert the array elements into a string. Below are the approaches to convert an array to a string in PHP: Table of Content Using implode() functionUsing json_encode() FunctionUsing sprintfUsing serialize() FunctionUsing implode() functionThe implode() method
2 min read
How to Convert Byte Array to String in PHP?
Given a Byte Array, the task is to convert the byte array to a String in PHP. It is used in various scenarios, such as processing binary data, handling file uploads, or working with data transmission protocols. Below are the approaches to convert byte array to string in PHP: Table of Content What is
3 min read
PHP Program to Convert Array to Query String
This article will show you how to convert an array to a query string in PHP. The Query String is the part of the URL that starts after the question mark(?). Example: Input: $arr = ( 'company' => 'GeeksforGeeks', 'Address' => 'Noida', 'Phone' => '9876543210');Output: company=GeeksforGeeks
3 min read
How to Convert Integer array to String array using PHP?
Given is an integer Array, the task is to convert the Integer array to a String array and print the output. Example: Input: $integerArray = [10, 20, 30, 40, 50];Output: ["10", "20", "30", "40", "50"]These are the following approaches: Table of Content Using the array_map() and strval() functionUsing
4 min read
How to Convert String to Camelcase in PHP?
Given a String containing spaces, the task is to Convert String to Camelcase in PHP. Converting a string to CamelCase is a common operation in PHP, especially when working with variable names or class names. CamelCase is a naming convention where the first letter of each word in a compound word is c
3 min read
How to convert array to SimpleXML in PHP
Many times need to store the data as a XML format into the database or into the file for later use. To fulfill this requirement need to convert data to XML and save XML file. The SimpleXML extension functions provides the tool set to convert XML to an object. Those objects deals with normal property
3 min read
How to trim all strings in an array in PHP ?
Given a string array with white spaces, the task is to remove all white spaces from every object of an array.Examples: Input: arr = ["Geeks ", " for", " Geeks "] Output: Geeks for Geeks Method 1: Using trim() and array_walk() function: trim() Function: The trim() function is an inbuilt function whic
3 min read
How to Convert Byte Array to JSON in PHP ?
Given a Byte Array, the task is to convert Byte Array into JSON using PHP. Converting a byte array to JSON in PHP is a common task, especially when dealing with binary data or when you want to represent raw data in a JSON format. Table of Content Using base64_encode() and json_encode() FunctionsUsin
2 min read
How to append a string in PHP ?
We have given two strings and the task is to append a string str1 with another string str2 in PHP. There is no specific function to append a string in PHP. In order to do this task, we have the this operator in PHP: Table of Content Using Concatenation assignment operator (".=")Using Concatenation O
4 min read
PHP Program to Convert Enum to String
Enumerations, or enums are a convenient way to represent a fixed set of named values in programming. In PHP, native support for enums was introduced in PHP 8.1. If you are working with an earlier version of PHP, or if you want to explore alternative approaches, you may need a way to convert enums to
2 min read