Echo selected value first - php

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

Related

PHP Select Option from Array list

im new to PHP and im trying this stuff for hours, I wanted to show the Array items to the Select Option. Here's the code:
<select name="state">
<?php
$arrstate=array
(
array("AK","Alaska"),
array("AL","Alabama"),
array("AR","Arkansas"),
array("AZ","Arizona"),
array("CA","California"),
array("CO","Colorado"),
array("CT","Connecticut"),
array("DC","District of Columbia"),
array("DE","Delaware"),
array("FL","Florida"),
array("GA","Georgia"),
array("HI","Hawaii"),
array("IA","Iowa"),
array("ID","Idaho"),
array("IL","Illinois"),
array("IN","Indiana"),
array("KS","Kansas"),
array("KY","Kentucky"),
);
for($lop=0;$lop<=49;$lop++)
{
if (strtoupper($lead_info['state'])==$arrstate[$lop][0])
{
echo "<option selected=\"selected\" value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";
}else{
echo "<option value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";
}
}
?>
</select>
But it seems it only shows ".$arrstate[$lop][1]."
What seems to be the problem?
try it
<?php
$arrstate = array
(
'AK' => 'Alaska',
'AL' => 'Alabama',
'AR' => 'Arkansas',
'AZ' => 'Arizona'
); ?>
<select>
<?php foreach($arrstate as $key => $value) { ?>
<option value="<?php echo $key; ?>" <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
<?php } ?></select>
<?php
$arrstate=array
(
"AK","Alaska",
"AL","Alabama",
"AR","Arkansas",
"AZ","Arizona"
);
?>
this is the easiest way...
<select>
<?php
foreach($arrstate as $key => $value) {
?>
<option value="<?php echo $key; ?>" <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
<?php
}
?>
</select>
You can retrieve from database like this example:
<select>
<?php $result = mysqli_query($conn, "SELECT * FROM categories");
while ($row = mysqli_fetch_array($result)) {
$categories = array($row["category"]);
$arrlength = count($categories);
for($x = 0; $x < $arrlength; $x++) {
echo "<option>";
echo $categories[$x];
echo "</option>";
}}?>
</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.
?>

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
}

Categories