Generates a URL-encoded query string from the associative (or indexed)
array provided.
Parameters
data
May be an array or object containing properties.
If data is an array, it may be a simple
one-dimensional structure, or an array of arrays (which in
turn may contain other arrays).
If data is an object, then only public
properties will be incorporated into the result.
Note:
The __toString() magic method is
not called when an object is evaluated. To use the string representation of an
object in the query string, the object must be explicitly cast to a string.
numeric_prefix
If numeric indices are used in the base array and this parameter is
provided, it will be prepended to the numeric index for elements in
the base array only.
This is meant to allow for legal variable names when the data is
decoded by PHP or another CGI application later on.
If encoding_type is
PHP_QUERY_RFC1738, then encoding is performed per
» RFC 1738 and the
application/x-www-form-urlencoded media type, which
implies that spaces are encoded as plus (+) signs.
If encoding_type is
PHP_QUERY_RFC3986, then encoding is performed
according to » RFC 3986, and
spaces will be percent encoded (%20).
Return Values
Returns a URL-encoded string.
Changelog
Version
Description
8.4.0
Prior to PHP 8.4.0, BackedEnum properties of
data were converted to objects, rather than their scalar equivalents.
Only the numerically indexed element in the base array "CEO" received a
prefix. The other numeric indices, found under pastimes, do not
require a string prefix to be legal variable names.
Example #4 Using http_build_query() with an object
<?php
class parentClass {
public $pub = 'publicParent';
protected $prot = 'protectedParent';
private $priv = 'privateParent';
public $pub_bar = null;
protected $prot_bar = null;
private $priv_bar = null;
public function __construct(){
$this->pub_bar = new childClass();
$this->prot_bar = new childClass();
$this->priv_bar = new childClass();
}
}
class childClass {
public $pub = 'publicChild';
protected $prot = 'protectedChild';
private $priv = 'privateChild';
}
$parent = new parentClass();
echo http_build_query($parent);
?>
The above example will output:
pub=publicParent&pub_bar%5Bpub%5D=publicChild
Example #5 Using http_build_query() with objects containing
__toString()
<?php
class Foo {
public $publicProperty = 'visible';
public function __toString() {
return "bar";
}
}
$params = array(
'a' => 'b',
'foo' => new Foo()
);
// Without casting, http_build_query reads the public properties
echo http_build_query($params) . "\n";
// With explicit casting, http_build_query uses the __toString() output
$params['foo'] = (string) new Foo();
echo http_build_query($params) . "\n";
?>
The above example will output:
a=b&foo%5BpublicProperty%5D=visible
a=b&foo=bar
See Also
parse_str() - Parse a string as a URL query string
parse_url() - Parse a URL and return its components