Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Array from URL param not behaving as expected

I have a URL parameter containing category IDs that I want to treat as an array which looks like this:

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

In PHP I am using this to get the array from the URL parameter:

$catIDs = $_GET['cat'];

When I do an echo gettype($catIDs); it shows that it is in fact being treated as an array, but when I do a print_r($catIDs); I am getting this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

But I am expecting this:

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

What am I missing here? Thanks!

>Solution :

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

cat[]=3,9,13

Yields:

["3,9,13"]

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

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

Yields:

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

Alternately, you could specify a single parameter that’s comma-separated:

cat=3,9,13

And then just split it:

$cat = explode(',', $_GET['cat']);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading