note 111158 added to function.http-build-query

From: Date: Mon, 21 Jan 2013 12:20:51 +0000
Subject: note 111158 added to function.http-build-query
Groups: php.notes 
Request: Send a blank email to php-notes+get-193295@lists.php.net to get a copy of this message
The http_build_query function does not implement properly the HTTP spec for array values. For: http_build_query(array('arr' => array('a', 'b'))); http_build_query gives you: arr[0]=a&arr[1]=b I have this simple function that implements the HTTP's expected format for the query string: buildQuery(array('arr' => array('a', 'b'))); Will give you: arr[]=a&arr[]=b As expected according to the HTTP spec. The helper function code is available below: function buildQuery(array $params, $parent = '') { $pairs = array(); foreach ($params as $key => $value) { if (!empty($parent)) { if (is_string($key)) { $key = $parent . '[' . urlencode($key) . ']'; } else { $key = $parent . '[]'; } } else { $key = urlencode($key); } if (is_string($value)) { $pairs[] = $key . '=' . urlencode($value); } elseif (is_numeric($value)) { $pairs[] = $key . '=' . $value; } elseif (is_array($value)) { $pairs[] = self::buildQuery($value, $key); } } return implode('&', $pairs); } PS: It would be possibly useful to have an level control in the recursion so we can avoid infinite looping. Best Regards, Fabrício José ---- Server IP: 69.147.83.199 Probable Submitter: 177.43.248.114 ---- Manual Page -- http://php.net/manual/en/function.http-build-query.php Edit -- https://master.php.net/note/edit/111158 Del: integrated -- https://master.php.net/note/delete/111158/integrated Del: useless -- https://master.php.net/note/delete/111158/useless Del: bad code -- https://master.php.net/note/delete/111158/bad+code Del: spam -- https://master.php.net/note/delete/111158/spam Del: non-english -- https://master.php.net/note/delete/111158/non-english Del: in docs -- https://master.php.net/note/delete/111158/in+docs Del: other reasons-- https://master.php.net/note/delete/111158 Reject -- https://master.php.net/note/reject/111158 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#193295) next »