How to Set an Option from Multiple Options or Array with Different Values to Views as Selected in Select Box Using PHP

How to set an option from multiple options or array with different values to views as selected in select box using PHP

The good news is, this is possible and in PHP is quite simple really. First we put all of our options and their respective values in an array like so:

<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');

Follow this by opening the select box and calling upon the options array in a foreach loop...

echo '<select>';
foreach($options as $view=>$value){

As you may have noticed the array contains fields that look like 'Large'=>'l' and the for each loop is calling upon the options as $view=>$value. $view represents the name field, in this case 'Large' and $value represents the value field 'l'. This is important if you expect the user to see different options in the select box than what the values are set at.

Next we create the variable $selected which is going to be used to determine if there is a match between $row['value'] and $value...

$selected=($row['value'] == $value)? "selected" : "";

This is the same as using an if and else statement to set the variable, but shorter. The first section after the variable is asking if $row['value'] is equal to $value, if it does then $selected="selected" else (:) $selected is set to blank.

Next we include the options. Because it is in the foreach loop, we only need one line to insert all of the options...

echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';

Remember the $selected variable in the last step? Each time the foreach loop goes through a section of the options array set at the beginning, it checks to see if $row['value'] equals $value. If it does then $selected will be set as selected and that particular option will be the one that is shown on page load. It continues through the rest of the array until all views and values have been scanned and returns their respective options.

Finally we close the foreach loop and the select box...

}
echo '</select>';

And there you have it, an automatic way to make a select box option set as selected. A similar pattern can be used for check-boxes, radio selectors, tabs and more.

The full code...

<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');

echo '<select>';

foreach($options as $view=>$value){
$selected=($row['value'] == $value)? "selected" : "";
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
}

echo '</select>';

Choosing selected values from array in select option tag

I guess you could use in_array. Consider the following:

<?php  foreach ($fields as $field) : ?>
<option value="<?= $field['field_name'] ?>" style="direction: rtl" <?php if(in_array($field['field_name'], $f_r)) {echo 'selected';} ?> ><?= $field['field_name'] ?></option>
<?php endforeach; ?>

Sorry for syntax - not on my computer but I hope you get the idea...

Multiple option and keeping selected value

I cleaned up your code a bit and rewrote it so you can test what happens when you submit the form. Try this and make sure the form outputs the correct id's that you selected.

<?php
require_once('include/database.php');

// read current record's data
try {
// prepare select query
$getUser = "SELECT id, firstname, lastname, profession FROM user WHERE user_type = 'therapist'";
$stmt = $con->prepare($getUser);

// execute our query
$stmt->execute();
// initialize options variable so that it doesn't get overwritten
$options = "";
// store retrieved row to a variable
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

// values to fill up our form
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$profession = $row['profession'];
/*use ".=" so that you add to the $options, rather than overwrite the last row*/
$options .= '<option value=' . $row['id'] . '>' . $row['firstname'] . ' ' . $row['lastname'] . ' - ' . $row['profession'] . '</option>';
}
}

// show error
catch (PDOException $exception) {
die('ERROR: ' . $exception->getMessage());
}
// echo selections on form submit
if(isset($_POST['submit'])) {
foreach($_POST['therapist'] as $selection) {
echo $selection . "\n";
}
?>

<div class="form-group col-sm-6 col-md-4">
<form action="" method="POST">
<label for="therapist"><strong>Senior Practitional / SP: </strong></label>
<select name="therapist[]" multiple>
<?php echo $options; ?>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
</div>

UPDATE

The ultimate cause of your problem is that you are trying to insert an array into a sql database. You cannot insert an array directly into a sql table, so you must convert the array BEFORE inserting its values. See my edit below.

if(isset($_POST['submit'])) {

// Use the implode() function to convert the array into a comma-delimited string
$therapists = implode(',', $_POST['therapist']);
// echo $therapists . "<br>"; // Uncomment this line to see how the imploded array looks
// Now you can include the therapists in your INSERT statement like so:
$sql = "INSERT INTO `table` (`column_name`) VALUES ('".$therapists."')";
}
?>

<div class="form-group col-sm-6 col-md-4">
<form action="" method="POST">
<label for="therapist"><strong>Senior Practitional / SP: </strong></label>
<select name="therapist[]" multiple>
<?php echo $options; ?>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
</div>

To Display Each Therapist in their Own Column

Once you have queried your table and returned the values stored in the therapists column, you can use the explode() function to convert the string back into an array to display each therapist in a new column per your comment.

Suppose you store those values in the variable $therapists:

$string_to_array = explode(",", $therapists);
// print_r($string_to_array); // Uncomment this line to see how the new array looks
// Should look like this: Array ( [0] => therapist1 [1] => therapist2 [2] => therapist3 [3] => therapist4 )

// Now loop through the array to display each name
$columns = ""; // Initialize $columns to avoid being overwritten
foreach ($string_to_array as $key => $value) {
$columns .= "<td>$value</td>";
}
?>
<!--Echo $columns in table row-->
<table>
<tr><?php echo $columns; ?></tr>
</table>

How to select an option based on value

Option 1:

$list .="<option value='$A $B' ". ($A == '1' ? 'selected : '') ."> $A,$B </option>";

Option 2:

$selected = $A == '1' ? 'selected : '';
$list .="<option value='$A $B' $selected> $A,$B </option>";

PHP Display Multi-Select From Array Values with Pre-Selected Options User Previously Saved

Thanks to everyone for all the help with this. Based on all the comments and responses, there were three issues with the original code:

  • I should have used <?php as opposed to <?
  • I should have used in_array
  • The HTML syntax for selected value in <option> tag was out of place

This updated code fully resolves all the issues and works as intended:

<?php
$allservices = array('amazon','facebook','twitter','reddit');
$selectedservices = explode(",", $blockedservices);

?><select name="services[]" multiple="multiple"><?php
foreach($allservices as $option){
if(!empty($selectedservices)){

if(in_array($option,$selectedservices)){
?><option value="<?php echo $option;?>" selected><?php echo $option;?></option><?php
}
else {
?><option value="<?php echo $option;?>"><?php echo $option;?></option><?php
}

}else{
?><option value="<?php echo $option;?>"><?php echo $option;?></option><?php
}
}

?></select>

Multiple select option into a PHP array

Use name as name="access_list[]" without space.

And you can get selected options with $_POST['access_list']

$_POST['access_list'] is array that contains selected options

PHP Is there a way to shorten this list of options when updating a record?

<?php
/**
* Coding-Style is PSR-1 and PSR-12 compliant.
* In this example, we dont make useage of any return value of the print function.
* Therfore, the echo-construct is prefered.
*/
$locations = [
'003' => 'Boston (Derry, Manchester & Worcester)',
'009' => 'New York (Kingston & Poughkeepsie)',
'011' => 'Philadelphia (Alntn,Atlc Cty,Bthlm,Rdng,Vinldn,Wldwd)',
'013' => 'Los Angeles (Barston, Corona & San Bernardino-Ontario)',
// add more entrys here
];

$currentActiveAdi = (isset($_REQUEST['adi']) ? $_REQUEST['adi'] : null);
?>

<html>
<body>
<select name="adi" id="adi">
<?php foreach ($locations as $adi => $location):?>
<option value="<?=$adi;?>" <?=($currentActiveAdi === $adi ? 'selected="selected"' : '');?>>
<?=$location;?>
</option>
<?php endforeach;?>
</select>
</body>
</html>

Catch array of HTML multiple select with PHP

Try changing the names of the fields on the form to the indices at which you want the desired result:

<form method="post">
<input type="text" name="vcgame[0]" id="vcgame_1" value="">
<select name="vccoun[0][]" id="vccoun_5" multiple="multiple">
<option value="1">West Indies</option>
<option value="2" selected="selected">India</option>
<option value="3" selected="selected">Australia</option>
</select>

<input type="text" name="vcgame[1]" id="vcgame_2" value="">
<select name="vccoun[1][]" id="vccoun_9" multiple="multiple">
<option value="4">Italy</option>
<option value="5" selected="selected">Germany</option>
</select>
</form>

Then $_POST output is:

Array
(
[vcgame] => Array
(
[0] => cricket
[1] => football
)
[vccoun] => Array
(
[0] => Array
(
[0] => 2
[1] => 3
)
[1] => Array
(
[0] => 5
)
)
)

Or even like this:

<input type="text" name="data[0][vcgame]" id="vcgame_1" value="">
<select name="data[0][vccoun][]" id="vccoun_5" multiple="multiple">
...
<input type="text" name="data[1][vcgame]" id="vcgame_2" value="">
<select name="data[1][vccoun][]" id="vccoun_9" multiple="multiple">
Array
(
[data] => Array
(
[0] => Array
(
[vcgame] => cricket
[vccoun] => Array
(
[0] => 2
[1] => 3
)
)
[1] => Array
(
[vcgame] => football
[vccoun] => Array
(
[0] => 5
)
)
)
)

How to set multiple select options by default from array

I think you may have a logic error. Try this as your loop:

foreach ($title as $opt) {
$sel = '';
if (in_array($opt, $mytitle)) {
$sel = ' selected="selected" ';
}
echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}


Related Topics



Leave a reply



Submit