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 string to boolean in PHP?
Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value. Examples: Input : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN); Output : true Input : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN); Output
2 min read
How to convert an array to CSV file in PHP ?
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the leng
2 min read
How to get string between two characters in PHP ?
A string is a sequence of characters stored in the incremental form in PHP. A set of characters, one or many can lie between any two chosen indexes of the string. The text between two characters in PHP can be extracted using the following two methods : Table of ContentUsing substr() Method: Using fo
4 min read
How to convert an Integer Into a String in PHP ?
The PHP strval() function is used to convert an Integer Into a String in PHP. There are many other methods to convert an integer into a string. In this article, we will learn many methods.Table of ContentUsing strval() function.Using Inline variable parsing.Using Explicit Casting.Using sprintf() Fun
3 min read
How to convert a String into Number in PHP ?
Strings in PHP can be converted to numbers (float/ int/ double) very easily. In most use cases, it won't be required since PHP does implicit type conversion. This article covers all the different approaches for converting a string into a number in PHP, along with their basic illustrations.There are
4 min read
How to read each character of a string in PHP ?
A string is a sequence of characters. It may contain integers or even special symbols. Every character in a string is stored at a unique position represented by a unique index value. Here are some approaches to read each character of a string in PHPTable of ContentUsing str_split() method - The str_
4 min read
How to Slice an Array in PHP?
In PHP, slicing an array means taking a subset of the array and extracting it according to designated indices. When you need to extract a subset of elements from an array without changing the original array, this operation comes in handy. PHP comes with a built-in function called array_slice() to he
2 min read
How to Convert Number to Character Array in PHP ?
Given a number, the task is to convert numbers to character arrays in PHP. It is a common operation when you need to manipulate or access individual digits of a number. This can be particularly useful in situations where you need to perform operations on the digits of a number, such as digital root
3 min read
PHP Change strings in an array to uppercase
Changing strings in an array to uppercase means converting all the string elements within the array to their uppercase equivalents. This transformation modifies the array so that every string, regardless of its original case, becomes fully capitalized.Examples:Input : arr[] = ("geeks", "For", "GEEks
3 min read
How to get a substring between two strings in PHP?
To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples: Input:$string="hey, How are you?"If we need to extract the substring between "How" and "you" then the output should be are Output:"Are"Input:Hey, Welcome to Geeks
4 min read