Home >Backend Development >PHP Tutorial >php http_build_query implementation tutorial_PHP tutorial
php http_build_query implementation tutorial
http_build_query
(in PHP 5)
http_build_query - Generate URL encoded query string
Description
String http_build_query (array $formdata [ , string $numeric_prefix [ , string $arg_separator ] ] )
Generates a URL-encoded query string provided from the association (or index) array.
Parameters
formdata
May be an array or object containing properties.
The form of an array may be a simple one-dimensional structure, or an array of arrays (who may also contain other arrays).
numeric_prefix
If a numeric index is used for a base display and this parameter is supplied, it will be prepended to the numeric index content of the base display only.
This is a legally allowed variable name when decoding data with PHP or other CGI applications.
arg_separator
arg_separator.output is used for separate arguments unless this argument is specified, then used.
Return value
Returns a URL encoded string.
Modify
Release Notes
5.1.2 arg_separator parameter supplement.
5.1.3 The square brackets are escaped.
Example
Example #1 Simple use http_build_query ( )
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
echo http_build_query($data, '', '&'); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
?>
Example #2 http_build_query() with numerically index elements.
$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' =>'hypertext processor');
echo http_build_query($data) . "n";
echo http_build_query($data, 'myvar_');
?>
The above example will output:
0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor
Example #3 http_build_query() with complex arrays
$data = array('user'=>array('name'=>'Bob Smith',
‘age’=>47,
'sex'=>'M',
'dob'=>'5/12/1956'),
'pastimes'=>array('golf', 'opera', 'poker', 'rap'),
'children'=>array('bobby'=>array('age'=>12,
'sex'=>'M'),
'sally'=>array('age'=>8,
'sex'=>'F')),
'CEO');
echo http_build_query($data, 'flags_');