0

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=%5B%221010%22%2C%221020%22%2C%221030%22%5D

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?

4
  • 2
    Just use json_decode? Commented Dec 29, 2022 at 7:34
  • I've tried json_decode, the result is the same. Commented Dec 29, 2022 at 7:37
  • Then edit your question and demonstrate your attempts. Commented Dec 29, 2022 at 7:39
  • @SebastianSimon, update: If i store the $_GET into a variable and json_decode the variable, it does not work, but if i json_decode the $_GET itself it works... now I feel stupid :) thanks Commented Dec 29, 2022 at 7:39

1 Answer 1

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.