PHP:ForEach 循环中的 IF 语句应用于后续条目

PHP: IF statement within ForEach loop applying to subsequent entries

我有一个 IF 语句来检查 ForEach 循环中的特定字符串,如果存在,则将 'selected' 添加到 <option> 输出,以便条目首先显示在 HTML select框。但是,当循环到达正确的记录时,它会添加 'selected' 每个后续的 <option> 记录。

function adminFillOption($options, $input) {
$output = "";
$selected = "";
//iterate through the array
foreach ($options as $value => $desc) {
    if ($input == $desc) {
        $selected = 'selected';
    };
    //Add an option for each elemement of the array to the output
    $desc = htmlspecialchars($desc);
    $output .= "\t\t\t\t\t\t<option value='$desc' $selected >$desc</option>\n";

}//end interation
return $output;
}

如有任何帮助,我们将不胜感激。

function adminFillOption($options, $input) {
    $output = "";
    foreach ($options as $value => $desc) {
        //Add an option for each elemement of the array to the output
        $desc = htmlspecialchars($desc);
        $output .= "\t\t\t\t\t\t<option value='$desc'";
        if ($input == $desc) $output .= ' selected';
        $output .= ">$desc</option>\n";
    }//end interation
    return $output;
}

您永远不会取消设置,因此每次迭代都会设置它。

当条件不满足时,尝试使用三元运算符将其设置为空。

$selected = ($input == $desc) ? 'selected' : '';

或者在循环中声明 $selected,在 if 之前,两者都可以。

所以代码会变成:

function adminFillOption($options, $input) {
$output = "";
//iterate through the array
foreach ($options as $value => $desc) {
    $selected = ($input == $desc) ? 'selected' : '';
    //Add an option for each elemement of the array to the output
    $desc = htmlspecialchars($desc);
    $output .= "\t\t\t\t\t\t<option value='$desc' $selected >$desc</option>\n";

}//end interation
return $output;
}

演示:https://eval.in/546236

这是因为,您只为 $selected 赋值一次(当它被选中时)。

并且在达到选择的那个之后,变量没有被修改。

改变

if ($input == $desc) {
 $selected = 'selected';
};

收件人:

if ($input == $desc) {
 $selected = 'selected';
}
else {
 $selected = '';
}

或者以下选项更好:

$selected = '';
if ($input == $desc) {
 $selected = 'selected';
}

三元运算符:

$selected = ($input == $desc) ? 'selected' : '';
function adminFillOption($options, $input) {
$output = "";
// $selected = ""; -----> not here
//iterate through the array
foreach ($options as $value => $desc) {
    $selected = ""; // ----> but here
    if ($input == $desc) {
        $selected = 'selected';
    };
    //Add an option for each elemement of the array to the output
    $desc = htmlspecialchars($desc);
    $output .= "\t\t\t\t\t\t<option value='$desc' $selected >$desc</option>\n";

}//end interation
return $output;
}

如果您这样做,$selected 将始终在每次迭代中重置