Reputation: 90
I have a list of areas (1000+) and i was wondering if there was a way i can do this easier with code instead of repeating each value.
<select>
<option value="apple" <?php if ($user_data["$area"] == apple){echo 'selected';} ?>>Apple
</option>
<option value="lemon" <?php if ($user_data["$area"] == lemon){echo 'selected';} ?>>Lemon
</option>
<option value="orange" <?php if ($user_data["$area"] == orange){echo 'selected';} ?>>Orange
</option>
<option value="banana" <?php if ($user_data["$area"] == banana){echo 'selected';} ?>>Banana
</option>
</select>
I.E. have the same piece of php code for each option instead of having to type in the name of the value each time
<?php if ($user_data["$area"] == option VALUE){echo 'selected';} ?>
Could you provide some code or ideas for what to look in tutorials, i have no idea how to start. Thank you!
Upvotes: 2
Views: 24189
Reputation: 2329
foreach ($areas as $key => $val)
{
$select.= '<option '; // opening the option tag
foreach ($selected_from_db as $keyselected => $valselected)
{
$val_fetch_from_array = $valselected == $val['campaignid'] ? 'selected' : '';
$select.= $val_fetch_from_array; // codes for selecting multiple values
}
$select.= ' value = "' . $val['campaignid'] . '">#' . $val['campaignid'] . '-' . $val['campaignname'] . '</option>'; // closing the option tag
}
Upvotes: 0
Reputation: 3675
All the solutions look good... Here's one more way though:
<select>
<?php
$areas = array('apple', 'lemon', 'orange', 'banana');
$areas_count = count($areas);
for ($i = 0; $i < $areas_count; $i++) {
echo '<option value="' . $areas[$i] . '"';
echo ($user_data[$area] == $areas[$i]) ? ' selected' : '';
echo '>' . ucwords($areas[$i]) . '</option>';
}
?>
</select>
Upvotes: 4
Reputation: 42969
Use an array:
$areas = array(
'apple' => 'Apple',
'lemon' => 'Lemon',
'orange' => 'Orange',
'banana' => 'Banana'
);
Then use that array to print the select:
<select>
<?php foreach ($areas as $value => $text): ?>
<option value="<?php echo $value; ?>" <?php if ($user_data[$area] == $value) {echo 'selected';} ?>><?php echo $text; ?>
</option>
<?php endforeach; ?>
</select>
I am using an associative array because I am assuming that you want to be able to customize the areas' text label, and that they will not only be a capitaized version of the value used to match the user data.
Upvotes: 3
Reputation: 2709
//pseudo
$arr = array("apple", "lemon", "orange", ...);
foreach($arr as $value) {
echo '<option value="'.$value;
if($user_data[$area] === $value) {
echo 'selected';
}
//echo {the end of your option field syntax}
}
Upvotes: 5