X10nD
X10nD

Reputation: 22050

If construct displaying only else value - PHP

Here is my statement:

if($row_x['xfield']==$_POST['x1'] AND $row_x['yfield']==$_POST['y'])
{
   echo "ok";
}
else {
   echo "invalid";
}

When both are not equal to each other, it must display 'invalid' else, 'ok'. But in this case it displays 'invalid' whether it is valid or not.

Any clues to why?

Upvotes: 1

Views: 99

Answers (4)

HTBR
HTBR

Reputation: 1023

You said 'when BOTH are NOT equal'... implying you would want to use '!=' instead of '==' in your comparisons. See this T/F chart for &&:

--------------
| X | && | Y |
--------------
| F | F  | F |
--------------
| F | F  | T |
--------------
| T | F  | F |
--------------
| T | T  | T |
--------------

The X statement must be true AND the Y statement must be true. In your example

$row_x['xfield']==$_POST['x1']

must be TRUE as well as

$row_x['yfield']==$_POST['y']

But if I read your question you will want to have both statements as FALSE to show 'invalid'. So you'll need to substitute '==' for '!=' in each statement.

Upvotes: 2

StaticVariable
StaticVariable

Reputation: 5283

its because the any of them is not true or both

you are using the &&/AND so both must be match since you are getting the else result it mean any of them is not equal or both

you can check this by below method

if($row_x['xfield']==$_POST['x1']){
   echo ' xfiekd  is = to x1';
   if($row_x['yfield']==$_POST['y']){
     echo ' yfiekd  is = to y and aslo 1 is true';
   }else{ echo 'y is false' }


}
else{
   echo ' xfiekd  is = to x1' is false;
   if($row_x['yfield']==$_POST['y']){
     echo ' yfiekd  is = to y and aslo 1 is true';
   }else{ echo 'y is false' }


}

to get in if function body on true at least one condition you need to use the || instead of the AND

difference betwen AND an OR

truth table for AND

  a    b

true  true   = true
true  false  = false
false  false = false
false  true  = false

truth table for OR

  a    b

true  true   = true
true  false  = true
false true   = true
false false  = true
true  false  = true

Upvotes: 1

Surace
Surace

Reputation: 711

if($row_x['xfield']==$_POST['x1'] OR $row_x['yfield']==$_POST['y'])
{
   echo "ok";
}
else {
   echo "invalid";
}

alternative

if($row_x['xfield']!=$_POST['x1'] AND $row_x['yfield']!=$_POST['y'])
{
   echo "ok";
}
else {
   echo "invalid";
}

Upvotes: 0

Alexander Larikov
Alexander Larikov

Reputation: 2339

Replace AND with OR and it'll show ok when at least one is equal

Upvotes: 1

Related Questions