Open In App

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&Address=Noida&Phone=9876543210

There are two methods to convert an array to query strings, these are:

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
  
$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.

Syntax:

string urlencode( $input )
rtrim( $string, $charlist )

Example: This example uses urlencode() and rtrim() methods to convert associative array into query sting.




<?php
  
// Crreate an Array
$arr = array(
    'company' => 'GeeksforGeeks',
    'Address' => 'Noida',
    'Phone' => '9876543210'
);
  
// Create an empty string
$queryStr = '';
  
// Loop to iterate array elements 
foreach ($arr as $key => $value) {
    $queryStr .= $key . '=' . urlencode($value) . '&';
}
  
// Remove the & symbol of right side
$queryStr = rtrim($queryStr, '&');
  
// Print the Query String
echo $queryStr;
  
?>

Output
company=GeeksforGeeks&Address=Noida&Phone=9876543210

Article Tags :