![]() |
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 = ( There are two methods to convert an array to query strings, these are: Table of Content Using http_build_query() MethodThe http_build_query() function is used to generate a URL-encoded query string from the associative (or indexed) array. Syntax: string http_build_query( Example: This example uses http_build_query() Method to convert associative array into query sting.
Output company=GeeksforGeeks&Address=Noida&Phone=9876543210 Using urlencode() and rtrim() MethodsFirst, 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 ) Example: This example uses urlencode() and rtrim() methods to convert associative array into query sting.
Output company=GeeksforGeeks&Address=Noida&Phone=9876543210 Using array_map() and implode() MethodsThis 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().
Output: company=GeeksforGeeks&Address=Noida&Phone=9876543210 Using array_reduce() MethodThe 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.
Output company=GeeksforGeeks&Address=Noida&Phone=9876543210 Using array_walk() MethodThe 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.
Output company=GeeksforGeeks&Address=Noida&Phone=9876543210 |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |