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:
Array ([0] => 3,9,13)
But I am expecting this:
Array ([0] => 3, [1] => 9, [2] => 13)
What am I missing here? Thanks!
CodePudding user response:
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']);