3

Let's say I have a bunch of checkbox inputs initially on a page like this:

<input type="checkbox" name="vehicle" value="Car" /> Car<br />
<input type="checkbox" name="vehicle" value="Bike" /> Bike<br />
<input type="checkbox" name="vehicle" value="Motorcycle" /> Motorcycle<br />
<input type="checkbox" name="vehicle" value="Bus" /> Bus<br />
<input type="checkbox" name="vehicle" value="Car" /> Train<br />

Now let's say that I have an array like this:

$my_array = array(
    'first' => 'Bike', 
    'second' => 'Car', 
    'third' => 'Train'
);

As you can see, my array contains values which correspond to the value of my checkboxes.

Now, how do I set the state of each checkbox input based on the value of my array and make the checkbox stay checked even on page refresh using php? In other words, I want to display all the checkboxes on my page but only those whose values match the value in my array should be checked on the page. Is this possible with just straight PHP or do I need javascript for this?

Any idea please? I have tried almost everything with no success

hakre
  • 193,403
  • 52
  • 435
  • 836
user765368
  • 19,590
  • 27
  • 96
  • 167

1 Answers1

7

Sure, you can do this with PHP...

<input type="checkbox" name="vehicle" value="Car" <?php if(in_array('Car', $my_array)) echo( 'selected = "selected"'); ?>/> Car<br />

Rinse and repeat for all of your checkboxes.

However, it would be smarter if you also kept an array containing all possible options. Then you could just iterate over that array and check each entry in that array to see if it also exists in your 'selected' array.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96