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.

2
  • 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. Commented Oct 3, 2021 at 10:14
  • I don't own the process that forms the query string. Commented Oct 4, 2021 at 12:26

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.