PHP Program to Convert Array to Query String
Last Updated :
24 Oct, 2023
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&Address=Noida&Phone=9876543210
There are two methods to convert an array to query strings, these are:
- Using http_build_query() Method
- Using urlencode() and rtrim() Methods
Using http_build_query() Method
The http_build_query() function is used to generate a URL-encoded query string from the associative (or indexed) array.
Syntax:
string http_build_query(
$query_data,
$numeric_prefix,
$arg_separator,
$enc_type = PHP_QUERY_RFC1738
)
Example: This example uses http_build_query() Method to convert associative array into query sting.
PHP
<?php
$arr = array (
'company' => 'GeeksforGeeks' ,
'Address' => 'Noida' ,
'Phone' => '9876543210'
);
$queryStr = http_build_query( $arr );
echo $queryStr ;
?>
|
Output
company=GeeksforGeeks&Address=Noida&Phone=9876543210
Using urlencode() and rtrim() Methods
First, we will create an empty string and then use foreach loop to merge key and encoded values with equals and & symbol and at least trim the & symbol from right side.
- The urlencode() function is used to encode the URL. This function returns a string which consist all non-alphanumeric characters except -_. and replace by the percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.
- The rtrim() function is used to remove the white spaces or other characters (if specified) from the right side of a string.
Syntax:
string urlencode( $input )
rtrim( $string, $charlist )
Example: This example uses urlencode() and rtrim() methods to convert associative array into query sting.
PHP
<?php
$arr = array (
'company' => 'GeeksforGeeks' ,
'Address' => 'Noida' ,
'Phone' => '9876543210'
);
$queryStr = '' ;
foreach ( $arr as $key => $value ) {
$queryStr .= $key . '=' . urlencode( $value ) . '&' ;
}
$queryStr = rtrim( $queryStr , '&' );
echo $queryStr ;
?>
|
Output
company=GeeksforGeeks&Address=Noida&Phone=9876543210
Share your thoughts in the comments
Please Login to comment...