search

Home  >  Q&A  >  body text

PHP arrays obtained from URL parameters do not behave as expected

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粉785905797P粉785905797228 days ago1662

reply all(1)I'll reply

  • P粉267791326

    P粉2677913262024-04-07 00:39:50

    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']);

    reply
    2
  • Cancelreply