HELP!!! IF Condition - Why is it true?

  • Thread starter Thread starter Anonymous
  • Start date Start date
A

Anonymous

Guest
I can't seem to figure out why the below IF statement is true. Based on the data in my array, the IF should be false and the subsequent code should not be executed. I am new to PHP, what am I missing??? (I've tested that the below values are what is actually in the array at the time of the IFs execution). I'm sure I've got some syntax error I don't know about. Are my use of 'and' & 'or' valid?

Relevent values from cardShape Array:

$cardShape[0] = 3;
$cardShape[6] = 3;
$cardShape[7] = 2;

if ((($cardShape[0] == $cardShape[6]) == $cardShape[7]) or
($cardShape[0] == 1 and $cardShape[6] == 2 and $cardShape[7] == 3) or
($cardShape[0] == 1 and $cardShape[6] == 3 and $cardShape[7] == 2) or
($cardShape[0] == 2 and $cardShape[6] == 1 and $cardShape[7] == 3) or
($cardShape[0] == 2 and $cardShape[6] == 3 and $cardShape[7] == 1) or
($cardShape[0] == 3 and $cardShape[6] == 1 and $cardShape[7] == 2) or
($cardShape[0] == 3 and $cardShape[6] == 2 and $cardShape[7] == 1))
{
echo "A Shape Match was found!";
}
 
Code:
$cardShape[0] = 3;
$cardShape[6] = 3;
$cardShape[7] = 2;

if (($cardShape[0] == $cardShape[6] && $charShape[0] == $cardShape[7] && $cardShape[6] == $cardShape[7])  ||
($cardShape[0] == 1 && $cardShape[6] == 2 && $cardShape[7] == 3) ||
($cardShape[0] == 1 && $cardShape[6] == 3 && $cardShape[7] == 2) ||
($cardShape[0] == 2 && $cardShape[6] == 1 && $cardShape[7] == 3) ||
($cardShape[0] == 2 && $cardShape[6] == 3 && $cardShape[7] == 1) ||
($cardShape[0] == 3 && $cardShape[6] == 1 && $cardShape[7] == 2) ||
($cardShape[0] == 3 && $cardShape[6] == 2 && $cardShape[7] == 1))
{
echo "A Shape Match was found!";
}
 
Please make your if condition structure neat. It is quite hard to read.
 
It was neat... this forum reformats text when you post, and eliminates spaces and tabs.
 
@tkdbb84 so the issue was with this statement:

($cardShape[0] == $cardShape[6]) == $cardShape[7])

I think I see it, but can you explain why?

My guess is:

(3 == 3) 2 - the comparison made in the parenthesis evaluates to true, which is not equal to 2.

So I'm still not sure how the IF statement evaluates to true (and why the code executes) but I see that it's not doing the same thing that I intended.

Correct me if I'm wrong, but ($cardShape[0] == $cardShape[6] && $cardShape[0] == $cardShape[7])
is all that is needed to ensure all 3 values are the same. In your example we're doing more work that isn't needed. Am I wrong?

Thanks for the help!
 
you are correct

(a == b) == c evaluates down to
(true) == c
or
(false) == c

both of which aren't going to work, unless C is a boolean.

and you are correct again

a == b == c is proven with only 2 comparisons
a == b && a==c

it was early i hadn't had my coffee yet.
 
Thank you for confirming and for the original suggestion as to why my code didn't work. Fixed my program and it's working great now!
 
Back
Top