Selecting an SELECT HTML item

Asked

Viewed 52 times

1

I’m trying to get the item selected which has the id equal to that of the $_REQUEST

$combo .= "<option value='".$row_area->area_id."' ".if($id == $row_area->area_id) { echo "selected"; } .">".$row_area->are_descricao."</option>";

But it’s just that you’re displaying that mistake: Parse error: syntax error, unexpected 'if' (T_IF), the complete code is like this:

for($j = 0; $j < $table_area->RowCount(); $j++) {
    $row_area = $table_area->getRow($j);
    $combo .= "<option value='".$row_area->area_id."' ".if($id == $row_area->area_id) { echo "selected"; } .">".$row_area->are_descricao."</option>";
}

1 answer

1


Do it with a ternary, otherwise you’re putting one echo inside a string concatenation and echo will come out first, alone. In fact I think this syntax would not even pass but however the correct way would be:

$selected = $id == $row_area->area_id ? "selected" : "";
$combo .= "<option value='".$row_area->area_id."' ".$selected.">".$row_area->are_descricao."</option>";

Another variant, correct but in my view less clean:

$combo .= "<option value='".$row_area->area_id."' ".($id == $row_area->area_id ? "selected" : "").">".$row_area->are_descricao."</option>";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.