简体   繁体   中英

How do I $GET multiple values with the same name from a url?

I have created a form using checkboxes with the method set to GET.

The results are example.com/careers/?career_type=val1&career_type=val2

<?= $_GET['career_type']; ?>

This only displays val2.

Is it possible to display both values?

While it's perfectly valid to have multiple parameters with the same name, PHP doesn't handle it very well. You have two options.

  1. Change the URL to use an array eg example.com/careers/?career_type[]=va1&career_type[]=val2 . Then $_GET['career_type'] will be returned as an array containing val1 and val2. If you're using a form to generate this URL, you can simply name your fields name="career_type[]"

  2. If that's not possible, you can manually parse the query string. This will have the same effect:

    $query = explode('&', $_SERVER['QUERY_STRING']);
    $params = [];
    foreach ($query as $param) {
        [$name, $value] = explode('=', $param, 2);
        $params[urldecode($name)][] = urldecode($value);
    }

    var_dump($params['career_type']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM