Use AND and OR operators on the same condition

Asked

Viewed 31 times

0

In the following example the check does not work if the page was sobre, in this case it displays the page servicos even though it is not the one requested in the validation. What’s wrong? I realized that this problem only happens in the elseif

$status = 1;
$pagina = "sobre";

if($pagina = "home" AND $status == 2 OR $status == 3) {

    echo "Página Home";

}elseif($pagina = "servicos" AND $status == 1 OR $status == 2) {

    echo "Página Serviços";

}elseif($pagina = "sobre" AND $status == 1 OR $status == 2) {

    echo "Página Serviços";

}

1 answer

2


in this case it displays the services page

Note that in $pagina = "home" you are attributing o a string home for the variable $pagina!

For comparisons, the operator is == (Compare the value) or === (Compare type and value).

Your condition should be changed too:

if($pagina == "home" AND ($status == 2 OR $status == 3)) { // ...

In conclusion, your code should be like this:

$status = 1;
$pagina = "sobre";

if($pagina == "home" AND ($status == 2 OR $status == 3)) {  // PAGINA DEVE SER "home" E STATUS DEVE SER 2 OU 3

    echo "Página Home";

} else if($pagina == "servicos" AND ($status == 1 OR $status == 2)) { // PAGINA DEVE SER "servicos" E STATUS DEVE SER 1 OU 2

    echo "Página Serviços";

} else if($pagina == "sobre" AND ($status == 1 OR $status == 2)) { // PAGINA DEVE SER "home" E STATUS DEVE SER 1 OU 2

    echo "Página Serviços"; // Página Sobre!!!

}
  • Thank you, I’ve come across this type of problem several times and always had to find alternative means to solve

Browser other questions tagged

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