PHP Program to Convert Array to Query String
Last Updated :
02 Aug, 2024
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
<?php
$arr = array(
'company' => 'GeeksforGeeks',
'Address' => 'Noida',
'Phone' => '9876543210'
);
$queryStr = http_build_query($arr);
echo $queryStr;
?>
Outputcompany=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
// 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;
?>
Outputcompany=GeeksforGeeks&Address=Noida&Phone=9876543210
Using array_map() and implode() Methods
This approach involves mapping the array elements to key-value pairs and then using implode to join them into a query string.
Example: The example usage demonstrates creating a query string using array_map() and implode().
PHP
<?php
$arr = array(
'company' => 'GeeksforGeeks',
'Address' => 'Noida',
'Phone' => '9876543210'
);
$queryStr = implode('&', array_map(
function($key, $value) {
return $key . '=' . urlencode($value);
},
array_keys($arr),
$arr
));
echo $queryStr;
?>
Output:
company=GeeksforGeeks&Address=Noida&Phone=9876543210
Using array_reduce() Method
The array_reduce() function iteratively reduces the array to a single string using a callback function.
Example: This example uses the array_reduce() method to convert an associative array into a query string.
PHP
<?php
$arr = array(
'company' => 'GeeksforGeeks',
'Address' => 'Noida',
'Phone' => '9876543210'
);
$queryStr = array_reduce(
array_keys($arr),
function($carry, $key) use ($arr) {
return $carry . $key . '=' . urlencode($arr[$key]) . '&';
},
''
);
// Remove the trailing & symbol
$queryStr = rtrim($queryStr, '&');
echo $queryStr;
?>
Outputcompany=GeeksforGeeks&Address=Noida&Phone=9876543210
Using array_walk() Method
The array_walk() function applies a user-defined function to every element of the array. In this approach, we'll build the query string by concatenating the key-value pairs within the callback function.
Syntax:
bool array_walk(array &$array, callable $callback, mixed $userdata = null)
Example: This example uses the array_walk() method to convert an associative array into a query string.
PHP
<?php
$arr = array(
'company' => 'GeeksforGeeks',
'Address' => 'Noida',
'Phone' => '9876543210'
);
$queryStr = '';
array_walk($arr, function($value, $key) use (&$queryStr) {
$queryStr .= $key . '=' . urlencode($value) . '&';
});
// Remove the trailing & symbol
$queryStr = rtrim($queryStr, '&');
echo $queryStr;
?>
Outputcompany=GeeksforGeeks&Address=Noida&Phone=9876543210
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Use Case Diagram - Unified Modeling Language (UML) A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read
Half Wave Rectifier A Half-wave rectifier is an electronic device that is used to convert Alternating current (AC) to Direct current (DC). A half-wave rectifier allows either a positive or negative half-cycle of AC to pass and blocks the other half-cycle. Half-wave rectifier selectively allows only one half-cycle of th
15 min read
What is Agile Methodology? The Agile methodology is a proper way of managing the project with breaking them into smaller phases which is iteration. It basically focus on flexibility of the project which we can change and improve the team work regularly as per requirements.Table of ContentWhat is Agile?What is the Agile Method
14 min read
PHP Tutorial PHP is a widely used, open-source server-side scripting language primarily designed for web development. It is embedded directly into HTML and generates dynamic content on web pages. It allows developers to handle database interactions, session management, and form handling tasks.PHP code is execute
9 min read
How to Download and Install the Google Play Store The Google Play Store is the heartbeat of your Android experienceâhome to millions of apps, games, and updates that keep your device functional, fun, and secure. But what if your phone or tablet doesnât have it pre-installed?In this step-by-step guide, youâll learn how to safely download and install
6 min read
Top 8 Software Development Life Cycle (SDLC) Models used in Industry Software development models are various processes or methods that are chosen for project development depending on the objectives and goals of the project. Many development life cycle models have been developed to achieve various essential objectives. Models specify the various steps of the process a
9 min read
IEEE 802.11 Architecture The IEEE 802.11 standard, commonly known as Wi-Fi, outlines the architecture and defines the MAC and physical layer specifications for wireless LANs (WLANs). Wi-Fi uses high-frequency radio waves instead of cables for connecting the devices in LAN. Given the mobility of WLAN nodes, they can move unr
9 min read
Transaction in DBMS In a Database Management System (DBMS), a transaction is a sequence of operations performed as a single logical unit of work. These operations may involve reading, writing, updating, or deleting data in the database. A transaction is considered complete only if all its operations are successfully ex
10 min read