-4
if($a=="" and $b=="" or $c=="") {
    echo "something";
}

I want to ask that if $a AND $b is empty then it will print: something. But if $b is not empty, then it will check the statement like this e.g. if $a is empty AND $c is empty then print: something (Means $a is compulsory to check with the variable which is empty $b OR $c)

Rizier123
  • 57,440
  • 16
  • 89
  • 140
  • @Rizier123 This isn't about using the spelled out names versus the operators. This question relates to precedence between `and` and `or`. He'd have the same problem if he used `&&` and `||`, he would still need parentheses. – Barmar Apr 16 '15 at 20:12
  • @Barmar your right, my fault. I was too quick then. – Rizier123 Apr 16 '15 at 20:14
  • 1
    http://php.net/manual/en/language.operators.precedence.php – Marc B Apr 16 '15 at 20:15

3 Answers3

1

See the PHP Operator Precedence table. and has higher precedence than or, so your condition is treated as if you'd written

if (($a == "" and $b == "") or ($c == ""))

Since you want the $a check to be independent, you need to use parentheses to force different grouping:

if ($a == "" and ($b == "" or $c == ""))

Note that in expressions, it's conventional to use && and || rather than and and or -- the latter are usually used in assignments as a control structure, because they have lower precedence than assignments. E.g.

$result = mysqli_query($conn, $sql) or die (mysqli_error($conn));

See 'AND' vs '&&' as operator

Community
  • 1
  • 1
Barmar
  • 669,327
  • 51
  • 454
  • 560
0

Just force the comparison order/precedence by using parentheses:

if( $a == "" and ( $b == "" or $c == "" ) )

But you would be better off using && and ||:

if( $a == "" && ( $b == "" || $c == "" ) )
AbraCadaver
  • 77,023
  • 7
  • 60
  • 83
0

I suppose you need something like this:

if (
    ($a == '')
    &&
    (
        ($b == '')
        ||
        ($c == '')
    )
   )

so, it will print something only when $a is empty and either $b or $c empty

Iłya Bursov
  • 21,884
  • 4
  • 31
  • 54