zaf
zaf

Reputation: 23244

Query string processing

While doing some query string processing I stumbled upon this:

<?php
$in='a=6&b=7&8=c';
parse_str($in,$qs);
$out=array_merge($qs,array('9'=>'d'));
print_r($out);
?>

We get:

Array
(
    [a] => 6
    [b] => 7
    [0] => c
    [1] => d
)

Instead of:

Array
(
    [a] => 6
    [b] => 7
    [8] => c
    [9] => d
)

I understand why this is happening ('8' and '9' are being treated as numeric keys) but I'm not happy that I have to do this the long way round.

There must be a way to keep it simple. How do you slice, dice and cook your query strings?

Upvotes: 4

Views: 444

Answers (4)

Yehonatan
Yehonatan

Reputation: 1172

Why dont you just do a simple loop over one array and checking of key exists or not?

If it exists then update the value otherwise add a new array element. Thats waht I do to avoid problems like these.

Upvotes: 1

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94143

The issue is that array_merge renumbers numeric keys so that they start from zero (if you var_dump your $qs array before the merge, you will see that there is a key named 8). Either don't use numeric keys, or just push straight onto the array instead of using array_merge:

$in = 'a=6&b=7&8=c';
parse_str($in,$qs);
$out = $qs;
$out[9] = 'd';

Note that parse_str also has the side effect of setting variables in the local scope, so after you parse your query string, $a will be 6 and $b will be 7. This may or may not be desired.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

Consider using the UNION operator for arrays

$out=$qs+array('9'=>'d');
print_r($out);

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157870

I am using http_build_query() function.
And NEVER use numeric keys for the query string/any request variables.

Upvotes: 1

Related Questions