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
How to Convert Query String to an Array in PHP?
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 [ad
4 min read
PHP Program to Convert String to ASCII Value
Given a String the task is to convert the given string into ASCII code using PHP. ASCII is the American Standard Code for Information Interchange, which is a widely used standard for encoding characters in computers and digital communication systems. There are two methods to convert a given String i
2 min read
How to Convert Array to String in PHP?
We are given an array and the task is to convert the array elements into a string. Below are the approaches to convert an array to a string in PHP:Table of ContentUsing implode() functionUsing json_encode() FunctionUsing sprintfUsing serialize() FunctionUsing implode() functionThe implode() method i
2 min read
How to Convert Byte Array to String in PHP?
Given a Byte Array, the task is to convert the byte array to a String in PHP. It is used in various scenarios, such as processing binary data, handling file uploads, or working with data transmission protocols. Below are the approaches to convert byte array to string in PHP:Table of ContentWhat is a
3 min read
PHP Program to Split & Join a String
Given a String, the task is to split and join strings in PHP. It is a common operations that allow you to manipulate and manage text data effectively. Below are the approaches to split and join a string in PHP: Table of Content Using explode() and implode() FunctionUsing str_split() and Custom Join
3 min read
How to Convert Integer array to String array using PHP?
Given is an integer Array, the task is to convert the Integer array to a String array and print the output.Example:Input: $integerArray = [10, 20, 30, 40, 50];Output: ["10", "20", "30", "40", "50"]These are the following approaches:Table of ContentUsing the array_map() and strval() functionUsing a l
4 min read
How to Convert String to Camelcase in PHP?
Given a String containing spaces, the task is to Convert String to Camelcase in PHP. Converting a string to CamelCase is a common operation in PHP, especially when working with variable names or class names. CamelCase is a naming convention where the first letter of each word in a compound word is c
3 min read
PHP Program to Sort an Array in Ascending Order
Sorting array elements is a common operation in programming. PHP provides several methods to achieve this operation. In this article, we will explore various approaches to sort array elements of an array in ascending order.Table of ContentUsing sort() FunctionUsing asort() FunctionUsing array_multis
3 min read
How to Convert a String to JSON Object in PHP ?
Given a String, the task is to convert the given string into a JSON object in PHP. JSON (JavaScript Object Notation) is a widely used data interchange format. PHP provides convenient functions to work with JSON data. Table of ContentUsing json_decode() to Convert to an ArrayHandling Errors with json
3 min read
How to Convert Byte Array to JSON in PHP ?
Given a Byte Array, the task is to convert Byte Array into JSON using PHP. Converting a byte array to JSON in PHP is a common task, especially when dealing with binary data or when you want to represent raw data in a JSON format. Table of Content Using base64_encode() and json_encode() FunctionsUsin
2 min read