Jump to content

Need help with my plugging array into scroll list code.


pxxb

Recommended Posts

Hi, I am trying to make a scroll list that is multi-selectable. I am having trouble generating the scroll list and having the array be in it. I am new to php so any help would be nice. Thank you.

 

$fruits = array(        "--" => "---Please Select a Fruit ---",
                        "ap"=>"Apple",
                        "ba"=>"Banana",
                        "ga"=>"Grapes",
                        "wa"=>"Watermelon",
                        "pe"=>"Pear");

 

<fieldset>
<legend> Fruits</legend>
<select name = "fruits">
<?php foreach ($fruits as $fruit){ ?>
<option value = ""><?php $fruit ?></option>
<?php } ?>
</select>
</fieldset>

I assume you have the $fruit = array(...) code wrapped in <?php and ?> tags? If you have then you you've almost got it. The <?php $fruit ?> should be <?php echo $fruit ?>.
 

If you want to set the value="" for each option, eg ap, ba, ga etc. Then the foreach loop construct needs to be foreach ($fruits as $key => $fruit) to retrieve the key value pairs from the $fruits associative array. Now you can do <option value="<?php echo $key; ?>"> to set each options value

 

Corrected code

<?php

$fruits = array(
    "--" => "---Please Select a Fruit ---",
    "ap" =>"Apple",
    "ba" =>"Banana",
    "ga" =>"Grapes",
    "wa" =>"Watermelon",
    "pe" =>"Pear"
);
?> 
<fieldset>
<legend> Fruits</legend>
<select name = "fruits">
<?php foreach ($fruits as $key => $fruit){ ?>
<option value = "<?php echo $key ?>"><?php echo $fruit ?></option>
<?php } ?>
</select>
</fieldset>

Thank you, it worked when I executed it seperately. This code is part of a bigger program that I am working on and for somereason it wont display the $fruits. :\ trying to figure out why haha

 

I assume you have the $fruit = array(...) code wrapped in <?php and ?> tags? If you have then you you've almost got it. The <?php $fruit ?> should be <?php echo $fruit ?>.
 

If you want to set the value="" for each option, eg ap, ba, ga etc. Then the foreach loop construct needs to be foreach ($fruits as $key => $fruit) to retrieve the key value pairs from the $fruits associative array. Now you can do <option value="<?php echo $key; ?>"> to set each options value

 

Corrected code

<?php

$fruits = array(
    "--" => "---Please Select a Fruit ---",
    "ap" =>"Apple",
    "ba" =>"Banana",
    "ga" =>"Grapes",
    "wa" =>"Watermelon",
    "pe" =>"Pear"
);
?> 
<fieldset>
<legend> Fruits</legend>
<select name = "fruits">
<?php foreach ($fruits as $key => $fruit){ ?>
<option value = "<?php echo $key ?>"><?php echo $fruit ?></option>
<?php } ?>
</select>
</fieldset>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.