'How'd I properly ampersand separate query string array param and format the URL along with it?

My code's causing some strange behavior and I'm not sure why.

For some reason, the http_build_query($valuesArr, '', '&'); line isn't separating with & and instead it's separating with %.

$values = $request->get('allValues');

$valuesArr = [
    'valueOne' => $values,
    'valueTwo' => $values
];

http_build_query($valuesArr, '', ','); // separating with `%` instead of `,`

$queryParams = ['allValues' => (object) $valuesArr]; // cast array to object

dd($queryParams);

Whenever I do dd($queryParams);, the result is (it's also missing the , to separate valueOne and valueTwo for some reason):

^ array:2 [
  {
     "valueOne" => "0684857340;0684857340429"
     "valueTwo" => "0684857340;0684857340429"
  }
]

How can I make it so that it looks like:

^ array:2 [
  {
      "valueOne" => "0684857340",
      "valueTwo" => "0684857340429"
  }
]

and the final url looks like (and optionally allow one value passed as well):

mySite.test/api?value=0684857340&0684857340429

Output of dd($request->get('allValues'));:

0684857340&0684857340429


Solution 1:[1]

If your format is always the same (number & number), then this should work.

$values = $request->get('allValues');
// string '0684857340&0684857340429'

$keysArray = ['valueOne', 'valueTwo'];
$valuesArray = explode('&', $values);
// array ['0684857340', '0684857340429']

$queryArray = array_combine($keysArray, $valuesArray);
// array ['valueOne' => '0684857340', 'valueTwo' => '0684857340429']

$query = http_build_query($queryArray);
// string 'valueOne=0684857340&valueTwo=0684857340429'

If you don't know how many numbers you'll get (number or number & number & number....), then maybe using an array would be better.

$values = $request->get('allValues');
// string '0684857340&0684857340429'

$valuesArray = explode('&', $values);
// array ['0684857340', '0684857340429']

$queryArray = ['values' => $valuesArray];
// array ['values' => [...]]

$query = http_build_query($queryArray);
// string  'values%5B0%5D=number1&values%5B1%5D=number2&values%5B2%5D=...'
// decoded 'values[0]=number1&values[1]=number2....

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1