Search code examples
phpassociative-array

How do I convert a string to an associative array when the string contains a duplicate key in PHP?


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.


Solution

  • 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);