Jump to content

Setting drop down based on 2d array


jwhite68

Recommended Posts

I have an array as follows:

 

$arr_subtype[0][0] = "Jam";
$arr_subtype[0][1] = "Custard";
$arr_subtype[1][0] = "Not applicable";
$arr_subtype[2][0] = "Pie";
$arr_subtype[2][1] = "Cake";
$arr_subtype[2][2] = "Sweet";

 

If the value of the first element is 0, I want to display Jam/Custard in the drop down, if the first element is 1, just display 'Not applicable' and if first element is 2, display the Pie,Cake and Sweet values in the drop down.

 

I also have values for the 2 array indexes in variables, based on when user has selected a value. So when the form is redisplayed, it displays the existing value.

$index1 and $index2 are the variables for the selected values.  Where $index1 is a higher level list earlier in the code.

 

The first entry will also display a 'Select type' initially, when the form is first displayed (before they have selected anything).

 

The code I need is something like:

 

select name="subtype" id="subtype" "<option value="" selected>Select type</option>
<?
foreach ($arr_subtype as $key => $value)
{
										if ($key==$index2) // display existing value if set as selected
            { 
										echo '<option value="'.$key.'" selected>'.$value.'</option>'; 
} 
else 
            { 
											echo '<option value="'.$key.'">'.$value.'</option>'; 
}
}
?>

 

I know this code isnt correct, and wondered if anyone code advise?

 

Its on an ADD form, that validates other form fields, and has to redisplay the drop downs with the previously selected values (ie remember previously entered values).

Link to comment
Share on other sites

select name="subtype" id="subtype">
<option value="">Select type</option>
<?php
foreach ($arr_subtype[$index1] as $indexVal => $optionVal)
{
    $selected=($index1==$indexVal)?' selected="selected"':'';
    echo "<option value=\"$indexVal\"$selected>$optionVal</option>";
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.