I'm having a hard time filtering out the excess "option" outputs here. I'm thinking I'm confusing myself.
foreach ($bv_wg_lf_rf_array_base as $bv_wg_lf_rf_arrayaaa) {
foreach ($bv_wg_lf_rf_array as $base) {
if ($bv_wg_lf_rf_arrayaaa == $base){
$bv_wg_lf_rf_arrayaaa = strtoupper($bv_wg_lf_rf_arrayaaa);
$me .= '<option value="'.$bv_wg_lf_rf_arrayaaa.'" selected>'
.$bv_wg_lf_rf_arrayaaa.'</option>';
}
else {
$base = strtoupper($bv_wg_lf_rf_arrayaaa);
$me .= '<option value="'.$bv_wg_lf_rf_arrayaaa.'">'
.$bv_wg_lf_rf_arrayaaa.'</option>';
}
}
}
echo $me;
This on dump returns (without excess)
WG
WG
WG
LF
LF
LF
RF
RF
RF
bv_wg_lf_rf_array_base =
array (size=3)
0 => string 'WG' (length=2)
1 => string 'LF' (length=2)
2 => string 'RF' (length=2)
bv_wg_lf_rf_array
array (size=3)
0 => string 'RF' (length=2)
1 => string '' (length=0)
2 => string '' (length=0)
The first array is a manually created array to determine the actual inputs while the second array is from the database. Three different columns for WG LF and RF is present(else null in db).
So basically it's spitting it out all three times rather than creating the selected option then erasing skipping and moving to the others that should be without selected.
First, you can reduce the array that comes from the database to a single value like this:
$selected = array_filter($bv_wg_lf_rf_array)[0];
Using array_filter without a callback will remove all of the empty string values from your array.
If you have an older PHP version, it may need to be done in two statements:
$selected_array = array_filter($bv_wg_lf_rf_array);
$selected = $selected_array[0];
It looks like this could be avoided if you changed the query that produces this array to only get the selected value from the database, but I am just working with what you have here.
This will significantly simplify building your option string.
foreach ($bv_wg_lf_rf_array_base as $value) {
// see if the value matches the selection
$selected = ($value == $selected) ? 'selected' : '';
// append the option with the appropriate 'selected' setting
$me .= "<option value=\"$value\" $selected>$value</option>";
}
If you need to handle multiple selections, you can just skip the array_filter
and use in_array
to check your selections like this:
foreach ($bv_wg_lf_rf_array_base as $value) {
$selected = (in_array($value, $bv_wg_lf_rf_array)) ? 'selected' : '';
$me .= "<option value=\"$value\" $selected>$value</option>";
}