Php option value - php

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!

//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}
}

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>

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.

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
}

Related

Pre Select an Option in a form based on variable?

<select name="radio_typ" id="radio_typ" >
<option value="P5100">P5100</option>
<option value="P5400">P5400</option>
<option value="P7100">P7100</option>
<option value="P7200">P7200</option>
<option value="700P">Jaguar 700p</option>
<option value="LPE200">LPE200</option>
<option value="XL200">XL200</option>
</select>
I'd like to be able to pre-select an option in a drop down menu based on a variable from a database which will already be set to the current setting. This form is for the purpose of editing the setting if needbe.
I tried inserting value="<?php echo $radio_typ;?> but that didn't seem to work.
Any hints as to how I could do this?
Thank you twofed.
That code didn't quite work, but I was able to figure out a solution that did based on that thought process.
<select name="radio_typ" id="radio_typ" >
<?php foreach ($options as $value => $name) {
if ($value == $radio_typ) {
$sel = "selected";
} else {
$sel = "";
}?>
<option value="<?= $value; ?>" <?= $sel; ?>><?= $name; ?></option>
<?php } ?>
</select>
I think, the best solution would be:
<?php
$radio_typ = "700P";
// value => name
$options = [
"P5100" => "P5100",
"P5400" => "P5400",
"P7100" => "P7100",
"P7200" => "P7200",
"700P" => "Jaguar 700p",
"LPE200" => "LPE200",
"XL200" => "XL200"
];
?>
<select name="radio_typ" id="radio_typ" >
<?php foreach ($options as $value => $name) { ?>
<option value="<?= $value; ?>"<?= ($value == $radio_typ) ? ' selected' : ''; ?>><?= $name; ?></option>
<?php } ?>
</select>

Using a PHP variable to determine a HTML select box choice

I have a select box that when the page loads it sets a value selected based upon a variable. I also have 2 IF statements that checks the variable and returns the results. Here is my code I am trying to do:
<select id="satbreak1" name="satbreak1">
<?php if ($trimmed_title[0] == "Guest")
{
echo ('<option selected value="#">Select One</option>');
echo ('<option value="y">Yes</option>');
echo ('<option value="n">No</option>');
}
if ($trimmed_title[0] != "Guest")
{
echo ('<option <?php if($trimmed_satBreakfast[0] == "") echo ("selected ") ; ?> value="#">Select One</option>');
echo ('<option <?php if($trimmed_satBreakfast[0] == "y") echo ("selected ") ; ?> value="y">Yes</option>');
echo ('<option <?php if($trimmed_satBreakfast[0] == "n") echo ("selected ") ; ?> value="n">No</option>');
}
?>
</select>
What I need to do is if $trimmed_title[0] == "Guest" then echo out the first part, but if $trimmed_title[0] != "Guest") then echo out the second part and also check what the status of $trimmed_satBreakfast[0] is and set the selected value.
What is the best / correct way to handle this?
The first part works fine but having an php script in a echo seems to fail.
I think this might do the trick - not tested but theoretically looks ok
<select id="satbreak1" name="satbreak1">
<?php
if ( $trimmed_title[0] == "Guest" ) {
echo '
<option selected value="#">Select One</option>
<option value="y">Yes</option>
<option value="n">No</option>';
} else {
$tsb=$trimmed_satBreakfast[0];
echo '
<option selected value="#" '.( $tsb=='' ? 'selected' : '' ).'>Select One</option>
<option value="y" '.( $tsb=='y' ? 'selected' : '' ) .'>Yes</option>
<option value="n"'.( $tsb=='n' ? 'selected' : '' ).'>No</option>';
}
?>
</select>
Something like this:
<?php
$options = array(
'values' => array('', 'y', 'n'),
'titles' => array('Select One', 'Yes', 'No')
)
$index = $trimmed_title[0] == 'Guest' ? 0 : array_search($trimmed_satBreakfast[0], $options['values']);
//if ($index === false) $index = 0;
$optHtml = array();
foreach($options['values'] as $i => $val) {
$selected = $index == $i ? 'selected' : '';
$optHtml[] = "<option $selected value=\"$val\">{$options['titles'][$i]}</option>";
}
$optHtml = implode("\n", $optHtml);
?>
<select id="id" name="name">
<?php echo $optHtml?>
</select>
or any other style to split html from php:
//if ($index === false) $index = 0;
...
?>
<select id="id" name="name">
<?php foreach($options['values'] as $i => $val) {?>
<option <?=$index==$i?'selected':''?> value="<?=$val?>">
<?=$options['titles'][$i]?>
</option>
<?php } ?>
</select>
In this case HTML not used in the common php code, but php used in HTML (only general template features: loop through data and echo it).
Common purpose of this is possibility to extract template part to separate file.
It is already PHP so you have to remove the php tags
echo ('<option '.($trimmed_satBreakfast[0] == "") ? : '"selected"' : ''.' value="#">Select One</option>');
echo ('<option '.($trimmed_satBreakfast[0] == "y") ? : '"selected"' : ''.' value="y">Yes</option>');
echo ('<option '.($trimmed_satBreakfast[0] == "n") ? : '"selected"' : ''.' value="n">No</option>');

HTML select option set selected default echo get value php

I have a simple HTML form with a simple select like this
<select name="myselect" selected="<?php echo $_GET['brand'];?>">
<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>
</select>
What I am trying to do is because its a search filtering results form if the user choose Samsung as default brand to search next page with filteres search results will the select option default selected Samsung and no other. If user select to search Motorola then the selected option default will be Motorola.
How do I fix this?
selected is attribute of option not select, so remove it from select tag, change to:
<?php $brand = trim( strtolower($_GET['brand']) ); ?>
<select name="myselect">
<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>
</select>
This is Simple Example of selected=selected by using foreach loop and ternary operators in php... use can easily understand and customize that code...
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
<option value="<?php echo $key;?>" <?php echo ($key == '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
<?php $selected_brand = $_GET['brand'];
$temp_str = '';
$temp_str .= '<select name="myselect">';
$brands_array = array("all" => "all brands", "samsung" => "Samsung", "motorola" => "Motorola");
foreach ($brands_array as $key => $value) {
if($key == $selected_brand){
// For selected option.
$temp_str .= '<option value="'.$key.'" selected>'.$value.'</option>';
} else {
$temp_str .= '<option value="'.$key.'">'.$value.'</option>';
}
}
$temp_str .= '</select>';
echo $temp_str; // Select box.
?>

Echo selected value first

I need to echo the selected value first in a form when user wants to make an update. I tried several variants:
1)
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt" >' ;
foreach ($opt as $i => $value) {
echo "<option value=\"$i\"";
if ($_REQUEST['up_opt'] == $i)
{
echo "selected" ;
}
echo ">$opt[$i]</option>" ;
}
echo '</select>' ;
?>
2)
<?php $opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
$edu = $_REQUEST['edu'];
<select name="up_opt">
<?php foreach ( $opt as $i=>$opt ) : ?>
<option value="<?php echo $i?>" <?php echo $i == $edu ? 'selected' : ''?>><?php echo $opt ?></option>
<?php endforeach; ?>
</select>
3)
<select name="up_opt">
<option value="1" <?php if ($_GET['1'] == 'option1') { echo 'selected'; } ?>>Opt1</option>
<option value="2" <?php if ($_GET['2'] == 'option2') { echo 'selected'; } ?>>Opt2</option>
<option value="3" <?php if ($_GET['3'] == 'option3') { echo 'selected'; } ?>>Opt3</option>
</select>
None of these variants echoes the checked value first. Can someone help me, tell me what is wrong or give me another variant?
Variant 3 is ok (but I'd rather use a loop instead of hard-coded options). Your mistake is that you compare 'option1', 'option2' and so one when your real values are '1', '2', '3'. Also as #ElefantPhace said, don't forget about spaces before selected, or you'll get invalid html instead. So it would be this:
<select name="up_opt">
<option value="1" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>>Opt1</option>
<option value="2" <?php if ($_GET['up_opt'] == 2) { echo ' selected="selected"'; } ?>>Opt2</option>
<option value="3" <?php if ($_GET['up_opt'] == 3) { echo ' selected="selected"'; } ?>>Opt3</option>
</select>
With loop:
<?php
$options = array(
1 => 'Opt1',
2 => 'Opt2',
3 => 'Opt3',
);
?>
<select name="up_opt">
<?php foreach ($options as $value => $label): ?>
<option value="<?php echo $value; ?>" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>><?php echo $label; ?></option>
<?php endforeach ?>
</select>
Here is all three of your variants, tested and working as expected. They are all basically the same, you were just using the wrong variable names, and different ones from example to example
1)
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt">';
foreach ($opt as $i => $value) {
echo "<option value=\"$i\"";
if ($_POST['up_opt'] == $i){
echo " selected";
}
echo ">$value</option>";
}
echo '</select>';
?>
2) uses same array as above
$edu = $_POST['up_opt'];
echo '<select name="up_opt">';
foreach ( $opt as $i => $value ){
echo "<option value=\"$i\"", ($i == $edu) ? ' selected' : '';
echo ">$value</option>";
}
echo "</select>";
3)
echo '<select name="up_opt">';
echo '<option value="1"', ($_POST['up_opt'] == '1') ? 'selected':'' ,'>Opt1</option>';
echo '<option value="2"', ($_POST['up_opt'] == '2') ? 'selected':'' ,'>Opt2</option>';
echo '<option value="3"', ($_POST['up_opt'] == '3') ? 'selected':'' ,'>Opt3</option>';
echo '</select>';

Best way to use PHP to re-populate selected option value after a failed form submission?

I have this form with 10 dropdown selections to choose from and a final checkbox disclaimer at the bottom.
So for example if the user selected all 10 answers and forgets to check the disclaimer box at the bottom and clicks submit, the form will come back with an error message that they didn't agree to the disclaimer but all the answers they had previously selected are gone and they would have to re-do that. I am trying to find a best practice way to handle this without repeating so much code...
What I have it works but it is crazy redundant especially if I will have 100 questions.
<select name="question1" id="question1">
<?php if ($question[0] == '0') {
$first = 'selected="selected"';
$second = '';
$third = '';
$fourth = '';
} elseif ($question[0] == '1') {
$first = '';
$second = 'selected="selected"';
$third = '';
$fourth = '';
} elseif ($question[0] == '2') {
$first = '';
$second = '';
$third = 'selected="selected"';
$forth = '';
} elseif ($question[0] == '3') {
$first = '';
$second = '';
$third = '';
$forth = 'selected="selected"';
}
?>
<option value="0" <?php echo $first; ?>>Answer 1</option>
<option value="1" <?php echo $second; ?>>Answer 2</option>
<option value="2" <?php echo $third; ?>>Answer 3</option>
<option value="3" <?php echo $fourth; ?>>Answer 4</option>
</select>
This is only for 1 question so you can imagine I would have to repeat that for all questions. There must be a better way to do this?
Thanks...
<option value="0" <?= ($question[0] == 0 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="1" <?= ($question[0] == 1 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="2" <?= ($question[0] == 2 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="3" <?= ($question[0] == 3 ? "selected='selected'" : ""); ?>>Answer 1</option>
Is usually how it's done.
As far as I know, there is no elegant solution. I tend to use conditional statements, such as;
<option value="0" <?=($question[0] == 0 ? ' selected' : '')?>>Answer 1</option>
Here's how I do it:
$array_existing_values = array(3,5);
$array_options = array(1,2,3,4,5);
foreach(array_options as $value)
{
$sel = null;
if (in_array($array_existing_values,$array_options)
{
$sel = ' selected ';
}
$html_options .= "<option value='$value' $sel>$value</option>";
}
Add validation to season.
Try this. Have $questions hold all the questions for the user like this:
$questions = array(
// The first question
array(
'question' => 'The 1st question?'
'answers' => array(
'answer 1',
'answer 2',
'answer 3',
'answer 4',
)
),
// The second question
array(
...
),
// etc
);
And $answer contains all the answers from the user like this:
$answer = array(1, 2, 3, 2, ... );
Then you can redraw all your questions like this:
foreach ($questions as $index => $question)
{
echo "<p>" . $question['question'] ."</p>\n";
echo "<select name='question" . $index . "' id='question" . $index . "'>\n";
foreach ($question['answers'] as $value => $answer)
{
echo "<option value='" . $value . "' " . ($value == $answer[$index] ? "selected='true'" : "") . ">" . $answer . "</option>\n";
}
echo "</select>";
}

Categories