How to insert an if / else into an echo?

3
echo '<option value="0" {if/else} >Em revisão</option>';
echo '<option value="1" {if/else} >Publicado</option>';

I would like to have a if/else condition to ask the database for the value and give a selected on the returned value. Can you help me?

It would be something like: if($resultado['status'] == 1) { echo 'selected=selected'; }

    
asked by anonymous 11.11.2015 / 12:37

6 answers

7

You can use it as follows:

echo '<option value="0" ' . (($resultado['status'] == 0) ? 'selected=selected' : '') . ' >Em revisão</option>';
echo '<option value="1" ' . (($resultado['status'] == 1) ? 'selected=selected' : '') . ' >Publicado</option>';
    
11.11.2015 / 12:49
8

Use sprintf and ternario

Code

$dadoBanco = 1;

$option = '<option value="%s" %s>%s</option>';

$selected = 'selected="selected"';

echo sprintf($option, 0, ($dadoBanco == 0) ? $selected : '', 'Em revisão');
echo sprintf($option, 1, ($dadoBanco == 1) ? $selected : '', 'Publicado');
    
11.11.2015 / 12:53
7

You can use if ternary, like this:

<?php
$selected = $resultado['status'] == 1 ? ' selected="selected"' : '';
echo '<option value="1" ' . $selected . '>Publicado</option>';
echo '<option value="0" ' . $selected . '>Em revisão</option>'; 
    
11.11.2015 / 12:54
4

For the selected attribute case I would make an expression with the function printf .

So:

  printf('<select %s></select>', $resultado['status'] == 1 ? 'selected' : '');

If this were in HTML itself, I would use the PHP print function, combined with an expression

So:

<select <?php $resultado['status'] == 1 && print 'selected' ?>></select>

Note: You can not do the same thing with echo

    
11.11.2015 / 13:17
2

It can be done that way.

<?php
$value='United States';
$selected = ($value)=='United States'?'selected':'';
echo "<select>";
echo "<option>Teste</option>";
echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
echo "</select>";
exit;
?>
    
11.11.2015 / 15:28
-3

I think this can help you

<?php

$valor_select = $_POST['select'];

$valor_compara = '1';

echo '<select name="select" id="select">';
foreach($array_select as $val){
    $sel = ($val == valor_select)?'selected="selected"':'';

    echo '<option value="'.$val.'" '.$sel.'>'.$val.'</option>';
}
echo '</select>';

?>
    
11.11.2015 / 12:42