1

Because of the way our application is built, there are sometimes duplicate keys in the URL query, like these two m keys: foo=bar&foz=baz&fom=bam&m=q50&m=350Z

They are then used to do something in JS.

I need to build an associative array from this string and retain the FIRST value of m, but any of the standard array functions I've tried end up overwriting m when reaching the second one, for example:

$n = preg_match_all('/(\w+)=([^&$]*)/', $_SERVER['QUERY_STRING'], $matches);
   
for($i=0; $i<$n; $i++)
{
    $params[$matches[1][$i]] = $matches[2][$i];
}
echo var_dump($params);

results in

array (size=4)
  'foo' => string 'bar' (length=3)
  'foz' => string 'baz' (length=3)
  'fom' => string 'bam' (length=3)
  'm' => string '350Z' (length=4)

Does anyone have an idea of how to retain all the other key/value pairs but keep the first m?

It should be noted that m won't always come at the end of the string, so I can't break out of the loop after I set the first m.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
oxwilder
  • 756
  • 5
  • 14
  • This is an XY Problem. Don't try to hack a solution for an unsuitably formed query string. Instead, fix the query string so that you don't need to hack a solution. – mickmackusa Oct 03 '21 at 10:14
  • I don't own the process that forms the query string. – oxwilder Oct 04 '21 at 12:26

1 Answers1

1

Check if there's already an element in the array with the key before adding it.

    for($i=0; $i<$n; $i++)
    {
        if (!isset($params[$matches[1][$i]])) {
            $params[$matches[1][$i]] = $matches[2][$i];
        }
    }
    var_dump($params);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Ahh, of course! I tried a version of that with `!empty($params[$matches[1]['m']])` to no effect, but I think trying to access it by ['m'] was the problem. Well done @Barmar, thanks. – oxwilder Oct 01 '21 at 19:26