0

Is there an option in PHP via (php.ini) probably to recognize a parameter passed multiple times in the URL as an array?

/cars.php?color=A&color=B

The above query should result in an array of colors ['A','B'] instead of the second parameter 'B' overwriting the first parameter 'A'

3 Answers 3

1

Use this:

/cars.php?color[]=A&color[]=B
             //^^        ^^

No need to enable anything in php.ini, accessing $_GET['color'] will return an array.

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

4 Comments

yup, i know that PHP uses this approach.. but is there an option to recognize the version without the [] as an array too?
I'm not aware of any such option.
You could parse the url manually, but the way you want to do this right now is not how the query params should be used in any language anywhere. Even this example seems wrong to me it should be separated with a comma color=A,B
It may seem wrong, but it is how PHP is designed. php.net/parse_str#example-5111 Parsing manually would seem to be the only method if the URL cannot be changed
0

You can get the get params as string using:

$_SERVER['QUERY_STRING'];

So you could do something like this:

foreach(explode("&", $_SERVER['QUERY_STRING']) as $params) {
        list($key,$val) = explode("=",$params);
        $getArray[$key][] = $val;
}

var_dump($getArray);

However, this is really ugly, and other alternatives should be used (e.g., comma separated values)

Comments

0

If you dont want chage your url, you can use this :

$url = 'http://www.test.com/cars.php?color=A&color=B';

$parse_url = parse_url($url);

$array_color = array();
if($parse_url['query']){


    foreach (explode('&',$parse_url['query']) as $parameter)
    {
        $explode = explode('=',$parameter);

        if($explode[0]=='color'){
            $array_color[] = $explode[1];
        }
    }
}

var_dump($array_color);

I dont recommend it but it's work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.