EmmyS
EmmyS

Reputation: 12138

Conditional in PHP not working correctly

I have a condition that basically says this:

If the type is 5, and EITHER the user status is not signed in OR the history count is 0 (OR both are true - user is not signed in AND history count is 0), do something (in this case, skip the following loop processing and jump to the next iterator).

I'm doing something wrong, because it's hitting the else, even when I don't think it should.

Here's the code:

if($row['type'] === 5 && ($_SESSION['appState']['user_state']['status'] <> STATE_SIGNED_IN ||  $historyRtn[0]['historyCnt'] === 0) ) {
    error_log("don't create");
    continue;
}
else {
    error_log("type: " . $row['type'] . "; appState: " .$_SESSION['appState']['user_state']['status'] . "; historyCount: " . $historyRtn[0]['historyCnt']  );
}

For all chunks of code where $row['type'] is 5, it's hitting the else, regardless of what the other values are. Here are the error logs that come from the else. (FYI, STATE_SIGNED_IN is set to "signed in".)

// this one incorrectly hits the else, as appState is not signed in and historyCount is 0
type: 5; appState: recognized unregistered; historyCount: 0  

// this one incorrectly hits the else, as appState is signed in, but historyCount is still 0
type: 5; appState: signed in; historyCount: 0

// this one correctly hits the else, as appState is signed in and historyCount is 1
type: 5; appState: signed in; historyCount: 1

How do I need to phrase the if statement so that it only hits the else if all three conditions are true? I'd rather not change the statement to say if type is 5 and appState is signed in and historyCount > 0 because it then requires an else (I only have the else there now for testing) and it would require moving all the rest of the loop code that this is running inside into the else - if I can evaluate the conditions where I DON'T want the loop to run inside the if, I can just use continue to skip only the items I don't want processed.

Upvotes: 0

Views: 70

Answers (2)

alwaysLearn
alwaysLearn

Reputation: 6950

in you code

if($row['type'] === 5 && ($_SESSION['appState']['user_state']['status'] <> STATE_SIGNED_IN ||  $historyRtn[0]['historyCnt'] === 0) )

you are using === operator instead of ==

=== will match the value as well as type

== will just match the values

so either user == or check for the types if they are equal or not

Upvotes: 1

Kermit
Kermit

Reputation: 34063

Since you're using ===, you're asking if $row[type] is equal to 5, and they are of the same type. You need to do a var_dump of $row to see what the data type is.

For example:

$row[type] = "5";
var_dump($row[type]);

Returns

string(1) "5"

Therefore, the types are probably not evaluating to true.

You could try casting like so:

if( (int)$row[type] === 5 ... )

Upvotes: 2

Related Questions