PHP arrays obtained from URL parameters do not behave as expected
P粉785905797
P粉785905797 2024-04-06 22:09:02
1
1
1661

I have a URL parameter that contains a category ID and I want to treat it as an array like this:

http://example.com?cat[]=3,9,13

In PHP I use this to get an array from a URL parameter:

$catIDs = $_GET['cat'];

When I do echo gettype($catIDs); it shows that it is actually treated as an array, but when I do print_r($catIDs); I Get the following results:

Array ([0] => 3,9,13)

But I expected this:

Array ([0] => 3, [1] => 9, [2] => 13)

What am I missing here? Thanks!

P粉785905797
P粉785905797

reply all(1)
P粉267791326

The error is not on the server/PHP side, but on the client/requester side. The given URL gives you an array containing one element, which is a comma-separated string:

cat[]=3,9,13

Yield:

["3,9,13"]

To specify an array via a URL parameter, you need to repeat the parameter name for each item:

cat[]=3&cat[]=9&cat[]=13

Yield:

["3","9","13"]

Alternatively, you can specify a comma-separated parameter:

cat=3,9,13

Then split it:

$cat = explode(',', $_GET['cat']);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template