2

What's the best method to output multiple "selected" for my form select based on the URL parameter?

In my URL I might have these parameters &carBrand=1607191|Acura&carbrand=1607185|Alpha Romeo

But when I submit the URL the only option selected is the second one. And for this form I need to have multiple car selections selected via the url.

    <?php $carBrand = !empty( $_GET['carBrand'] ) ? $_GET['carBrand'] : ''; ?>

    <select name="brands[]" id="selectBrands" class="form-control" multiple="multiple">
      <option value="1607191|Acura" <?php echo $carBrand == '1607191|Acura' ? 'selected' : ''; ?>>Acura</option>
      <option value="1607185|Alpha Romeo" <?php echo $carBrand == '1607185|Alpha Romeo' ? 'selected' : ''; ?>>Alpha Romeo</option>
      <option value="1607197|Aston Martin" <?php echo $carBrand == '1607197|Aston Martin' ? 'selected' : ''; ?>>Aston Martin</option>
      <option value="1607188|Audi" <?php echo $carBrand == '1607188|Audi' ? 'selected' : ''; ?>>Audi</option>
      <option value="1607200|BMW" <?php echo $carBrand == '1607200|BMW' ? 'selected' : ''; ?>>BMW</option>
      <option value="1607194|Bentley" <?php echo $carBrand == '1607194|Bentley' ? 'selected' : ''; ?>>Bentley</option>
      <option value="1607203|Bugatti" <?php echo $carBrand == '1607203|Bugatti' ? 'selected' : ''; ?>>Bugatti</option>
      <option value="1607206|Buick" <?php echo $carBrand == '1607206|Buick' ? 'selected' : ''; ?>>Buick</option>
    </select>
  • Your url should have `[]` notation: `&carBrand[]=1607191|Acura&carBrand[]=1607185|Alpha` In this case you can use `in_array` to check for a value. – u_mulder Mar 13 '17 at 20:57
  • You can't have multiple carBrands arguments, try to use the array notation as already mentioned by u_mudler. Check out this answer http://stackoverflow.com/questions/6243051/how-to-pass-an-array-within-a-query-string – dinhokz Mar 13 '17 at 21:14

1 Answers1

2

Urls like &carBrand=1607191|Acura&carBrand=1607185|Alpha are treated in following way: each following value of carBrand= overwrites previous one. To have array of carBrand values, you need to use [] notation in your url, i.e:

&carBrand[]=1607191|Acura&carBrand[]=1607185|Alpha   

See [] after each carBrand? This is what you need.

After that your code can be written like:

<?php $carBrand = !empty( $_GET['carBrand'] ) ? $_GET['carBrand'] : array(); ?>

I use array() for default value so as later in_array function won't throw errors.

And your <select> code will be:

<select name="brands[]" id="selectBrands" class="form-control" multiple="multiple">
  <option value="1607191|Acura" <?php echo in_array('1607191|Acura', $carBrand) ? 'selected' : ''; ?>>Acura</option>
  <option value="1607185|Alpha Romeo" <?php echo in_array('1607185|Alpha Romeo', $carBrand) ? 'selected' : ''; ?>>Alpha Romeo</option>
  <!-- More options here -->
</select>
u_mulder
  • 54,101
  • 5
  • 48
  • 64