0

I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.

However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.

Currently, however I do it is:

STRING

?foo=bar&hello=world

Then on the server side, I would do:

<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>

Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.

Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?

3
  • 1
    ?object[foo]=bar&object[hello]=world Commented May 30, 2017 at 17:09
  • @AbraCadaver Thanks, that does seem to work. What about sending a an array as one of the values as in ?object[foo]=1&object[foo]=2. That would be the last clarification needed. Thank you! Commented May 30, 2017 at 17:11
  • 1
    object[foo][]=1&object[foo][]=2 Commented May 30, 2017 at 17:14

1 Answer 1

1

You can use an associative array in a form and in the query string:

object[foo]=bar&object[hello]=world

To build it URL encoded:

$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);

Yields:

object%5Bfoo%5D=bar&object%5Bhello%5D=world

You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array

object[foo][more][even more][]

Or:

object[foo][][more][even more]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.