search

Home  >  Q&A  >  body text

Fix if condition php & and or in same if scope

Tried adding & and or in the same if but the or condition doesn't work

else if ($usuario = 12 & $banca <=3 or =>7){
    echo "ok";
    }

is only valid when $banca <=3, but is invalid when $banca >=7 What's wrong?

The range I'm trying to check is between <=3 和 >=7

P粉218775965P粉218775965439 days ago621

reply all(1)I'll reply

  • P粉257342166

    P粉2573421662023-09-16 00:35:37

    There are some problems with your code. A simpler one and a more complex one: syntax and operator precedence.

    First of all, operator = is used for assignment, not comparison. Therefore, the result of $usuario = 12 is 12. Next, you have a bitwise operator & that outputs 0 if $banca > 3, otherwise 12. Finally, you take the result and check if it is >= 7. In other words: using them without knowing the operator won't do you any good. Please delve into the php language.

    Although your syntax works in PHP, operator precedence can also mess up the results. Check out PHP's operator precedence. This is one reason why linters and best practices manuals will instruct you to add parentheses to make your criteria clear, rather than relying on obscure operator precedence.

    Now, how do we solve this problem? Again, please take a closer look at PHP's operators and their syntax. There are some good courses out there, as well as the Official PHP Manual. But don't leave you hanging, your situation should look like this:

    if ($usuario === 12 && ($banca <= 3 || $banca >= 7)) { ... }

    reply
    0
  • Cancelreply