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", array(), "baz");
$qs = http_build_query($args);
echo $qs; // outputs 0=foo&1=bar&3=baz, I expected 0=foo&1=bar&2=&3=baz
This presents a problem for me, since I'm passing some data to an internal API over http and I need to pull all the arguments out on the other side.
Well, I googled this and came up with the following bug report: http://bugs.php.net/bug.php?id=50407 . The terse reply from an admin is, "Not setting is same as setting it empty. No bug."
Can somebody explain to me why this is not a bug? Does anyone have any ideas for a workaround, aside from the lame hack of setting an arbitrary value on one side and interpreting that value as an empty value on the other?
EDIT
Here's why I think it's a bug:
$args = array("foo", "bar", array(), "baz");
$qs = http_build_query($args);
parse_str($qs, $query);
echo ($args == $query); // false, I expect it to be true
I guess perhaps it's naive of me to consider parse_str()
and http_build_query()
to be inverses of one another.
I'm posting my current "lame hack" solution as an answer below.