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?

1
  • 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 Commented Jun 20, 2018 at 11:08

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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 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: php.net/manual/en/function.filter-input.php
Thanks. I see there is a FILTER_REQUIRE_ARRAY filter flag. Would this be safer when dealing with $_POST than using array_filter() ? php.net/manual/en/function.array-filter.php
I don't know about the broken way PHP processes parameters, but Java provides a simple way to transmit arrays of values: request.getParameterValues("my_array_of_values")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.