Using a PHP variable to determine a HTML select box choice - php

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>');

Related

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>';

How to embed if statement inside echo [duplicate]

This question already has answers here:
if block inside echo statement?
(4 answers)
Closed 11 months ago.
I'm gettin' a headache on that. I need to put if statement inside an echo (this echo is in a function, it's for a form submit actually)
Here is an example on a partial of my code. In this situation, how can I put theses if statement inside my echo??
<?php echo '<td><select id="depuis" name="depuis">
<option value=\'4\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'4\'){ echo \'selected\'; } else { echo ''; } ?> ></option>
<option value=\'1\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'1\'){ echo \'selected\'; } else { echo ''; } ?> >2 ans et moins</option>
<option value=\'2\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'2\'){ echo \'selected\'; } else { echo ''; } ?> >2 à 5 ans</option>
<option value=\'3\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'3\'){ echo \'selected\'; } else { echo ''; } ?> >5 ans et plus</option>
</select>
</td>'
; ?>
Everything is php so need to use more than the first <?php Finish each echo before checking with if. Like this:
<?php
echo '<td><select id="depuis" name="depuis">
<option value="4"';
if(isset($_POST['depuis']) && $_POST['depuis'] == '4') {
echo ' selected';
}
echo ' >Something here maybe?</option>...etc
Use an inline if statement:
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');
This would work - although I'm sure it could be streamlined:
<?php
$out = '
<td>
<select id="depuis" name="depuis">
<option value="4"
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '4'){
$out .= 'selected';
}
$out .= '
></option>
<option value='1'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '1'){
$out .= 'selected';
}
$out .= '
>2 ans et moins</option>
<option value=\'2\'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '2'){
$out .= 'selected';
}
$out .= '
>2 à 5 ans</option>
<option value='3'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '3'){
$out .= 'selected';
}
$out .= '
>5 ans et plus</option>
</select>
</td>
';
echo $out;
?>
Meilleurs voeux...
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
You shouldn't escape the array keys in the string
if(isset($_POST[\'depuis\']) ...
Should be
if(isset($_POST['depuis']) && ...
Also you could clean up the the generation of the options with a array and a loop
$options = array(
'label1' => 1,
'label2' => 2,
'label3' => 3,
'label4' => 4
);
$value = (isset($_POST['depuis'])) ? $_POST['depuis'] : 0;
foreach ($options as $label => $optionValue) {
$selected = ($optionValue == $value) ? ' selected' : '';
printf('<option value="%s"%s>%s</option>', $optionValue, $selected, $label);
}
Not sure you can do that like you're asking. You'd just need to use regular if/else if block and output the outcome separately.
<?php
echo("<td><select id=\"depuis\" name=\"depuis\">");
echo("<option value='4'");
if(isset($_POST['depuis']) && $_POST['depuis'] == '4'){ echo("selected"); }
echo("></option>");
[ ...etc... ]
?>

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

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>";
}

Issue with 'selected' value within form

I currently have a form built in which after validation, if errors exist, the data stays on screen for the consumer to correct. An example of how this works for say the 'Year of Birth' is:
<select name="DOB3">
<option value="">Year</option>
<?php
for ($i=date('Y'); $i>=1900; $i--)
{
echo "<option value='$i'";
if ($fields["DOB3"] == $i)
echo " selected";
echo ">$i</option>";
}
?>
</select>
If an error is found, the year of birth value returns the year previously entered. I am able to have this work on all field with the exception of my 'State' field. I build the array and function for the drop down with the following code:
<?php
$states_arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"District Of Columbia",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa", 'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming");
function showOptionsDrop($array, $active, $echo=true){
$string = '';
foreach($array as $k => $v){
$s = ($active == $k)? ' selected="selected"' : '';
$string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";
}
if($echo) { echo $string;}
else { return $string;}
}
?>
I then call the function from within the form using:
<td><select name="State"><option value="">Choose a State</option><?php showOptionsDrop($states_arr, null, true); ?></select></td>
Not sure what I'm missing but would love any assistance if somebody sees the error in my code.
Thanks!
Have a look at the code:
<?php showOptionsDrop($states_arr, null, true); ?>
You are passing null, so $active will always be null. The condition
($active == $k)
will never we evaluate to true.
You should pass the value you get from the form instead, e.g.:
<?php showOptionsDrop($states_arr, isset($fields['State']) ? $fields['State'] : null, true); ?>
You really should try to separate the PHP from the HTML, especially in your first example
Update:
Actually it is not that much, but consider to use the alternative syntax for control structures:
<select name="DOB3">
<optgroup label="Year">
<?php for ($i=date('Y'); $i>=1900; $i--) : ?>
<option value="<?php echo $i ?>"
<?php echo ($fields["DOB3"] == $i) ? 'selected="selected"' : '' ?> >
<?php echo $i ?>
</option>
<?php endforeach; ?>
</optgroup>
</select>
Also if you want to give the options some kind of label, you can do this with the optgroup HTML tag (this is not selectable).

Categories