IF syntax inside an ECHO

Asked

Viewed 4,787 times

2

I’m having a syntax problem trying to place a if within a echo in PHP.

Check out the code:

foreach($resultadoBusca as $escrever){
    echo "<tr><td>" . $escrever['cod_votoran'] . "</td>
    <td>" . utf8_encode($escrever['empresa_user']) . "</td>
    <td>" . utf8_encode($escrever['cidade_user']) . "</td>
    <td>" . $escrever['estado_user'] . "</td>
    <td>" . $escrever['fone_user'] . "</td>
    <td>" . $escrever['cpfcnpj_user'] . "</td>
    <td>" . $escrever['email_user'] . "</td>
    <td>" . $escrever['status_user'] . "</td>
    <td>".if($escrever['status_user']=='ativo'){."<a href=\"ativarUsuario.php?cod=".$escrever['cod_user']."\"><i class=\"icon-check\" title=\"Ativar Usuário!\"></i></a>"}."<a href=\"editarUsuario.php?cod=".$escrever['cod_user']."\"><i class=\"icon-edit\" title=\"Editar Usuário!\"></i></a><a href=\"excluirUsuario.php?cod=".$escrever['cod_user']."\"><i class=\"icon-remove\" title=\"Remover Usuário!\"></i></a></td></tr>";
}      

I know the mistakes are happening right where the if. Because if I take it off it works normally. Error that occurs like this.

2 answers

13

To use if inside an echo, needs to make use of a ternary operator all between parentheses: ( (condição) ? true : false )


$id = 1;
echo 'Olá ' . ( ($id === 1) ? 'id-1' : 'id-2' );

output: Ola id-1

More about ternary operator

  • Is there a reason the down vote?

  • 4

    Also did not understand the down. Simple and direct answer.

  • 2

    No doubt, this answer was more direct the question.

  • 1

    Congratulations @Papacharlie great response

8


You can’t for a if within a echo. The function echo is for printing strings, and you cannot put code (instructions) inside a string otherwise it won’t work.

It is appropriate to finish the echo whenever you want for more code:

foreach($resultadoBusca as $escrever){
    echo "<tr><td>" . $escrever['cod_votoran'] . "</td>
    <td>" . utf8_encode($escrever['empresa_user']) . "</td>
    <td>" . utf8_encode($escrever['cidade_user']) . "</td>
    <td>" . $escrever['estado_user'] . "</td>
    <td>" . $escrever['fone_user'] . "</td>
    <td>" . $escrever['cpfcnpj_user'] . "</td>
    <td>" . $escrever['email_user'] . "</td>
    <td>" . $escrever['status_user'] . "</td>
    <td>";
    if($escrever['status_user']=='ativo')
    {
        echo "<a href=\"ativarUsuario.php?cod=".$escrever['cod_user']."\"><i class=\"icon-check\" title=\"Ativar Usuário!\"></i></a>"
    }
    echo "<a href=\"editarUsuario.php?cod=".$escrever['cod_user']."\"><i class=\"icon-edit\" title=\"Editar Usuário!\"></i></a>";
    echo "<a href=\"excluirUsuario.php?cod=".$escrever['cod_user']."\"><i class=\"icon-remove\" title=\"Remover Usuário!\"></i></a></td>
                        </tr>";
}     
  • This answer served :D Thank you Jorge.

Browser other questions tagged

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