Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php option value

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!

like image 287
Wrostran Avatar asked Apr 26 '26 09:04

Wrostran


2 Answers

//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}
}
like image 122
Cristian Cavalli Avatar answered Apr 29 '26 01:04

Cristian Cavalli


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>
like image 41
jerdiggity Avatar answered Apr 29 '26 01:04

jerdiggity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!