Selecting a SELECT HTML item

1

I'm trying to leave the selected item which has id equal to $_REQUEST

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

But it's only showing this error: Parse error: syntax error, unexpected 'if' (T_IF) , the complete code looks 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>";
}
    
asked by anonymous 11.05.2016 / 16:24

1 answer

1

Do this with a ternary, otherwise you are putting echo into a string concatenation and echo will come out first, alone. Actually I think that this syntax would not even go by the way 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>";
    
11.05.2016 / 16:26