I'm looking for the name of the PHP function to build a query string from an array of key value pairs. Please note, I am looking for the built in PHP function to do this, not a homebrew one (that's all a google search seems to return). There is one, I just can't remember its name or find it on php.net. IIRC its name isn't that intuitive.
5 Answers
4 Comments
Calmarius
This is a quite new function, available from PHP 5.
cb0
Be careful with this function! It will omit any key-value pair where the value is NULL.
echo http_build_query(array("foo"=>"bar","bar"=>null)) will produce only foo=barTJ L
@cb0 this works similar to form submits in a browser, an empty input field will not be included in the submitted query.
Andrew
@ceejayoz Well you've known it for a long time now... Your wish has come true?
Here's a simple php4-friendly implementation:
/**
* Builds an http query string.
* @param array $query // of key value pairs to be used in the query
* @return string // http query string.
**/
function build_http_query( $query ){
$query_array = array();
foreach( $query as $key => $key_value ){
$query_array[] = urlencode( $key ) . '=' . urlencode( $key_value );
}
return implode( '&', $query_array );
}
2 Comments
cloudfeet
When doing its decoding, PHP appears to percent-decode the key as well. Possibly worth doing that here?
0x6A75616E
@cloudfeet seems reasonable to do so. Thanks for pointing it out.
Just as addition to @thatjuan's answer.
More compatible PHP4 version of this:
if (!function_exists('http_build_query')) {
if (!defined('PHP_QUERY_RFC1738')) {
define('PHP_QUERY_RFC1738', 1);
}
if (!defined('PHP_QUERY_RFC3986')) {
define('PHP_QUERY_RFC3986', 2);
}
function http_build_query($query_data, $numeric_prefix = '', $arg_separator = '&', $enc_type = PHP_QUERY_RFC1738)
{
$data = array();
foreach ($query_data as $key => $value) {
if (is_numeric($key)) {
$key = $numeric_prefix . $key;
}
if (is_scalar($value)) {
$k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($key) : rawurlencode($key);
$v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($value) : rawurlencode($value);
$data[] = "$k=$v";
} else {
foreach ($value as $sub_k => $val) {
$k = "$key[$sub_k]";
$k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($k) : rawurlencode($k);
$v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($val) : rawurlencode($val);
$data[] = "$k=$v";
}
}
}
return implode($arg_separator, $data);
}
}
Comments
Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.
2 Comments
Robin Barnes
Tried that but it won't work. I'm trying to build an http query string which requires both the keys and the values from the array, implode can't do this.
Ali
I see, wasn't sure if you meant an SQL query string or a http query string.