3

I have a php array....

<?php $state = array("Kentucky", "Ohio", "West Virginia", "Indiana", "Texas");

How would I get this aray to report to this select list.

<select size="1" name="state" id="state">
 <option>Select One</option>
</select>
1
  • 2
    Use foreach and echo. See the manual for examples Commented Feb 11, 2011 at 0:43

3 Answers 3

2
<?php 
$state = array("Kentucky", "Ohio", "West Virginia", "Indiana", "Texas");
?>

<select size="1" name="state" id="state">
<option>Select One</option>
<?php 
   foreach($state AS $val){
       echo "<option>$val</option>";
   }
 ?>
</select>

Should do the trick

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

Comments

1
<select size="1" name="state" id="state">
<?php
foreach($state as $state_name)
{
   echo '<option value="' . $state_name . '">' . $state_name . '</option>';
}
?>
</select>

3 Comments

you wouldn't need the value attribute if it is just the same as the text
I knew it was a foreach loop but I was not so sure how to use it. So when you use a for each loop you have to name it something else?
@Michael: Yes, you define the array you're going to iterate through and the variable that will store the current iteration value. Read more about foreach
1

You can implode (expand the array)

<select size="1" name="state" id="state">
<option>Select One</option>
<option>
<?php
  $state = array("Kentucky", "Ohio", "West Virginia", "Indiana", "Texas");
  echo implode('</option><option>', state);
?>
</option>
</select>

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.