Skip to content

Instantly share code, notes, and snippets.

@marcocesarato
Last active May 20, 2019 14:02
Show Gist options
  • Save marcocesarato/4293986fe93139f04d8269aa3fbd47e9 to your computer and use it in GitHub Desktop.
Save marcocesarato/4293986fe93139f04d8269aa3fbd47e9 to your computer and use it in GitHub Desktop.
Build URL query params as http_build_query build a query url the difference is that this function is array recursive and compatible with PHP4
<?php
/**
* Build URL query params
* as http_build_query build a query url the difference is
* that this function is array recursive and compatible with PHP4
*
* @author Marco Cesarato <cesarato.developer@gmail.com>
* @param $query
* @param string $parent
* @return string
*
* @example
* $p = array('abbreviations' => array('google' => 'ggle', 'facebook' => array('abb_key' => 'fbook', 'fcbk')), 'key' => 'value');
* echo url_build_query($p);
*/
function url_build_query($query, $parent = null){
$query_array = array();
foreach($query as $key => $value){
$_key = empty($parent) ? urlencode($key) : $parent . '[' . urlencode($key) . ']';
if(is_array($value)) {
$query_array[] = url_build_query($value, $_key);
} else {
$query_array[] = $_key . '=' . urlencode($value);
}
}
return implode('&', $query_array);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment