Home > Back-end >  how to make PHP interpret URL GET parameters as array?
how to make PHP interpret URL GET parameters as array?

Time:12-29

I'm trying to interpret an array url param in PHP, but it's interpreted as string instead of an array.

On client side, the url is generated with js: URL:

let url = window.location.href.split('?')[0] //example https://www.test.com

The get parameters are added with:

const params = encodeURIComponent(JSON.stringify(array));

url = "?array=" params;

for an example array of [1010,1020,1030], the final url looks like:

https://www.test.com?array=["1010","1020","1030"]

On server side (PHP), I'm using $_GET['array'] to get those data, the output looks like:

string(22) "["1010","1020","1030"]"

It is a syntactically correct array, but interpreted as string. I know, I could use some string manipulations to get the array I want, but is there a way, that I can get an array right from scratch?

CodePudding user response:

Either decode the current parameters as JSON...

$array = json_decode($_GET['array']);

or encode the array in a way PHP understands natively...

const params = new URLSearchParams();
array.forEach((val) => {
  params.append("array[]", val); // note the "[]" suffix
});
url  = `?${params}`;
$array = $_GET['array'] ?? [];
  • Related