I’ve fount this implementation of a function to convert an array to a URL. It seems correct and, in fact, it works pretty well in many cases, except when I pass an array value with a 0 value. This is the function:
function strtourl($arr, $entity = true, $prefix = '') {
$params = array();
foreach ($arr as $k => $v)
if ($v) {
$params[] = is_array($v) ? strtourl($v, $entity, $prefix ? $prefix.'['.$k.']' : $k) :
sprintf($prefix ? $prefix.'[%s]' : '%s', urlencode($k)).'='.urlencode($v);
}
return implode($entity ? '&' : '&', $params);
}
This is an example I’m using:
$array = array(
'type' => 0,
'content' => array(
'msg_id' => 'XSS120',
'source' => 0,
'dest' => 4,
'type' => 0,
'msg' => 'message'
)
);
It returns this string:
content[msg_id]=XSS120&content[dest]=4&content[msg]=message
instead of this:
type=0&content[msg_id]=XSS120&content[source]=0&content[dest]=4&content[type]=0&content[msg]=message
What’s happening and how to fix it?
if ($v) {is your problem. 0 evaluates to false, so it’s being skipped.I suggest removing that
if, it’s unneeded.