prepopulate a dropdown form list

invisible777

New member
Jul 3, 2007
1,331
17
0
If I'm passing this in my url &state=NJ how do I get it to prepopulate "NJ" in a drop down box? I tried php echo get for the value.. didn't work

I think its something along these lines, but this code blows up:

PHP:
       <option value="AL" <?php if (substr($_GET['state'], == AL) { echo "selected=\"selected\""; } ?>></option>
 


Code:
 <?php
  
 // add more states
 $states = array('AL', 'AK', 'AS', 'AZ', 'AR', 'CA');

 ?>

 <form name="form1" action="file_name.php" method="post">
  <select name="select1">

  <?php
  foreach ($states as $state)
  {
    ?>
    <option value="<?php echo $state ?>" <?php if ($state == strtoupper($_GET['state'])) { echo 'selected="selected"'; } ?>><?php echo $state ?></option>
    <?php
  }
  ?>
  </select>
  <input type="submit" />
  </form>
 
LogicFlux's answer is complete, but why your code blew off is because of a syntax error:

Code:
<option value="AL" <?php if (substr($_GET['state'], == AL) { echo "selected=\"selected\""; } ?>></option>
This part: substr($_GET['state'],
should be just $_GET['state']

and also == AL should be == 'AL'