1

I have an array of parameter values (with matching parameter names) in my request URL, like this:

?my_array_of_values=First&my_array_of_values=Second

In a Java servlet, I can detect them like this:

ServletRequest request = ...;
String[] myArrayOfValues = request.getParameterValues("my_array_of_values");

And this will result in:

myArrayOfValues[0] = "First";

myArrayOfValues1 = "Second";

...which is what I want.

However, I am not sure how to get the same results in PHP. For the same (above) parameters, when I try:

print_r($_GET); 

it results in

Array ( [my_array_of_values] => Second )

...i.e., the "First" parameter is lost.

I can see why this happens, but is there a way to detect such an array of parameter values in PHP as you can in Java/servlets? If not, is there a recommended workaround or alternative way of doing it?

Community
  • 1
  • 1
ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253
  • If you use a framework like laravel this is possible. Or you have manually write a method. BTW what about $_GET ? this is also a key value array – User123456 Jun 20 '18 at 11:08

1 Answers1

2

I don't know about the strange magic that happens in a Java environment, but query params must have different names or else they will overwrite each other.

In the example of ?my_array_of_values=First&my_array_of_values=Second only the last given value is returned. It is the same as assigning different values to the same variable one after the other.

You may retrieve a single parameter as array though, by using angle brackets after the parameter name:

?my_array_of_values[]=First&my_array_of_values[]=Second

In that case $_GET['my_array_of_values'] will be an array with all the given values.

See also: Authoritative position of duplicate HTTP GET query keys

feeela
  • 29,399
  • 7
  • 59
  • 71
  • Is there a 'safe' way of accessing `$_GET['my_array_of_values']`? I have tried using `filter_input(INPUT_GET, 'my_array_of_values')` (and `filter_input(INPUT_GET, 'my_array_of_values[]')`) but no joy. – ban-geoengineering Jun 20 '18 at 14:53
  • @ban-geoengineering You forgot to set the wanted filter – which is the third argument to `filter_input`: “If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.”; see: http://php.net/manual/en/function.filter-input.php – feeela Jun 20 '18 at 14:57
  • Thanks. I see there is a `FILTER_REQUIRE_ARRAY` filter flag. Would this be safer when dealing with **$_POST** than using `array_filter()` ? http://php.net/manual/en/function.array-filter.php – ban-geoengineering Jun 20 '18 at 16:13