Cindy
Cindy

Reputation: 11

PHP $_GET should return array instead of string

I have a strange error with a $_GET Value. I'm using this code for a query: array($_GET['cats'])

If I insert the get parameter manually, like: array(3,328) everything works fine. But if I use: array($_GET['cats']) and submit the cats by URL like ?cats=3,328 it does not work. What could be the issue?

Upvotes: 1

Views: 229

Answers (6)

Awaaaaarghhh
Awaaaaarghhh

Reputation: 201

Solution 1: Send HTTP GET parameters as an array in your URL

URL: parameters ?cats[]=3&cats[]=328

var_dump($_GET["cats"]) will result in:

array(2) {
  [0]=>
  string(1) "3"
  [1]=>
  string(3) "328"
}

Solution 2: Send numbers as one string in URL and process it with PHP

URL parameters: ?cats=3,328

... and then process it with some PHP code:

$cats = array_map("intval", explode(",", $_GET["cats"]));

var_dump($_GET["cats"]) will result in:

array(2) {
  [0]=>
  string(1) "3"
  [1]=>
  string(3) "328"
}

Upvotes: 1

Gumbo
Gumbo

Reputation: 655269

array($_GET['cats']) will create an array containing the single element that’s value is the value of $_GET['cats'], no matter what value it is. In case of the string value 3,328 is would be identical to array('3,328').

If you want to turn the string value 3,328 into an array identical to array(3,328), use explode to split the string at , into strings and array_map with intval to turn each string into an integer:

$arr = array_map('intval', explode(',', $_GET['cats']));

Now this resulting array is really identical to array(3,328):

var_dump($arr === array(3,328));  // bool(true)

Upvotes: 4

Nev Stokes
Nev Stokes

Reputation: 9779

As others have said, $_GET['cats'] is a string as you're doing things at the moment.

However, if you change your URI querystring to ?cats[]=3,328 then $_GET['cats'] will be the array(3,328) ready for you to use.

Upvotes: 1

Timo Haberkern
Timo Haberkern

Reputation: 4439

You need to split up the GET-Parameters

$values = explode(',', $_GET['cats'])

Upvotes: 0

Marwelln
Marwelln

Reputation: 29413

$_GET['cats'] is a simple string. If you want to get 3 and 328 as seperate values you need to use explode. You can than use foreach to print your exploded values.

Upvotes: 0

reko_t
reko_t

Reputation: 56430

You can't plug a value like that. array($_GET['cats']) is equivalent to array('3,328'), if the value of $_GET['cats'] is 3,328. So basically, the value is a string, not a list of integers. What you want is:

explode(',', $_GET['cats'])

Upvotes: 4

Related Questions