How to Convert Query String to an Array in PHP ?
Last Updated :
16 Nov, 2023
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&Phone=9876543210"
Output: Array (
[name] => xyz
[address] => noida
[mobile] => 9876543210
)
Input: str = "name=xyz&language=english&age=23&education=btech"
Output: Array(
[name] => xyz
[language] => english
[age] => 23
[education] => btech
)
There are two methods to convert a query string to an array, these are:
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 = "name=xyz&address=noida&mobile=9876543210" ;
parse_str ( $query , $res );
print_r( $res );
?>
|
Output
Array
(
[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.
PHP
<?php
$query = "name=xyz&address=noida&mobile=9876543210" ;
$arr = array ();
parse_str ( $query , $arr );
print_r( $arr );
?>
|
Output
Array
(
[name] => xyz
[address] => noida
[mobile] => 9876543210
)
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:
Share your thoughts in the comments
Please Login to comment...