Category: Post a PHP snippet
Build Querystring from an array in PHP4 and 5
PHP5 has a great built in function to build a querystring from an array, called http_build_query ( http://www.php.net/http-build-query ), However this isn't available in PHP.
This function will build a query from any given array, just like the http_build_query function. If the function is available it will use the built in http_build_query, otherwise it will use its own method for making the query.
Simple to use, just call:
http_parse_query( $array )
<?php
function http_parse_query( $array = NULL, $convention = '%s' ){
if( count( $array ) == 0 ){
return '';
} else {
if( function_exists( 'http_build_query' ) ){
$query = http_build_query( $array );
} else {
$query = '';
foreach( $array as $key => $value ){
if( is_array( $value ) ){
$new_convention = sprintf( $convention, $key ) . '[%s]';
$query .= http_parse_query( $value, $new_convention );
} else {
$key = urlencode( $key );
$value = urlencode( $value );
$query .= sprintf( $convention, $key ) . "=$value&";
}
}
}
return $query;
}
}
?>
example usage:
$values = array(
'act' => 'home',
'settings' => array(
'thread' => 20,
'post' => 10
)
);
$querystring = http_parse_query( $values );
$url = 'mysite.com/index.php?' . $querystring;
echo $url;
outputs:
mysite.com/index.php?act=home&settings[thread]=20&settings[post]=10