http_build_query()

Build a URL query string from an array

http_build_query() converts an array or object into a URL-encoded query string. PHP_QUERY_RFC3986 uses percent encoding such as %20 for spaces.

$params = [
    'name' => 'John Doe',
    'page' => 2,
];
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
echo $query;

Do not concatenate untrusted values directly into HTML; escape the finished URL when inserting it into markup.

We can use http_build_query function to use an array and create query string using all its elements. This output is already urlencoded and output string can be used in a URL to pass data to another page.

To generate the query string let us use this example. We have created an array with data from address book. Next line we use the same array to build the query string using http_build_query() function.
$ar=array("FName"=>"John","Address"=>"Street No 11 ","City"=>"Rain 
Town","Country"=>"USA");
echo http_build_query($ar);
The Output of above script is here
FName=John&Address=Street+No+11+&City=Rain+Town&Country=USA
Now this above string is ready to post through any URL. Here is an example.
<a href=anypage.php?FName=John&Address=Street+No+11+&City=Rain+Town
&Country=USA>Send Address</a>
Inside any script development we will be using dynamic data to generate the string and pass it through URL , so here is the complete code.


<?Php
$ar=array("FName"=>"John","Address"=>"Street No 11 ","City"=>"Rain 
Town","Country"=>"USA");
$str=http_build_query($ar);
echo "<a href=anypage.php?$str>Send Address</a>";
?>
Note that your array can be from a database table and similar way you can generate script to pass each address to any application.

Example: Creating Query String from Nested Arrays

$data = [
    'user' => 'john',
    'preferences' => ['theme' => 'dark', 'notifications' => 'on']
];
echo http_build_query($data);
// Output: user=john&preferences%5Btheme%5D=dark&preferences%5Bnotifications%5D=on

Example: Custom Encoding

$data = ['name' => 'John Doe', 'email' => 'john@example.com'];
echo http_build_query($data, '', '&', PHP_QUERY_RFC3986);
// Output: name=John%20Doe&email=john%40example.com

Array REFERENCE


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer