I ran into a problem today where I was passing a key with the value set to an empty array to http_build_query()
. E.g.:
$args = array(\"foo\", \"bar\
This is my current "lame hack" solution. Note I had to account for the possibility of nested arrays, so my example original array is slightly different from what I posted in the question:
$args = array("foo", "bar", array("red", "blue", array(), "green"), "baz");
$original_array = $args; // save it to compare later
function replace_empty_array_with_fake_string(&$value, $key) {
if (is_array($value)) {
if (empty($value)) {
$value = 'array()';
} else {
array_walk($value, 'replace_empty_array_with_fake_string');
}
}
}
array_walk($args, 'replace_empty_array_with_fake_string');
$qs = http_build_query($args);
// convert the query string back to an array, this would happen on the "other side"
parse_str($qs, $query);
function replace_fake_string_with_empty_array(&$value, $key) {
if ($value == 'array()') {
$value = array();
}
if (is_array($value)) {
array_walk($value, 'replace_fake_string_with_empty_array');
}
}
array_walk($query, 'replace_fake_string_with_empty_array');
echo ($original_array == $query); // true
Presumably I could come up with a more arbitrary string than "array()" to use as the placeholder.
Lame, I know.