OR in a PHP IF statement

I am having problems with my IF statement, it is always TRUE, although this is not true. I use the OR operator since there are two possible scenarios that I want to write in the IF statement.

The ad_status array string is "1", but with a return below -3, I expect IF to be FALSE. If I remove OR and the second statement from IF, the result of IF is correct.

How am I wrong? Thank.

    if(($getadstatus['ad_status'] != "1" || $getadstatus['ad_status'] != "4"))
    {
        return -3;
        exit;
    }

Optional: What I want to do is exit the function (not fully visible here) if ad_status is not 1 or 4. If it is any other value than 1 or 4, the IF statement should return TRUE and exit. ad_status can be any value from 0 to 4.

+3
source share
8 answers

, , not 1 OR is not 4 true.

"1"

if( 1 != 1 || 1 != 4)

if( false || true )

, , .

:

if(!($value == 1 || $value==4))

, ( )

if($value != 1 && $value != 4)
+8

.

ad_status == 1, If

$getadstatus['ad_status'] != "4"

, return -3;

, , AND

if ( $a!= 1 AND $a!= 4 )
+2

:

ad_status != 1 -> FALSE
ad_status != 4 -> TRUE

if (FALSE OR TRUE) TRUE.

, , OR AND:

if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
    return -3;
    exit;
}
+2

, "1" "4".

+2

&&, !=. ||, :

if (!($getadstatus['ad_status'] == "1" || $getadstatus['ad_status'] == "4"))

+2

&&

if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
    return -3;
    exit;
}
+2

in_array OR IF statemements. :

$array = array(1,4);

if (!in_array($getadstatus['ad_status'], $array)) {
 // do whatever

 }
+1

humm, , , . . IF . ad_status 1 4, -3 .

, , , , :

$status = $getadstatus['ad_status']; // assign a variable as it makes things easier to read.
if ( !( $status==1 || $status==4 ) )
{
    return -3;
}

, ! (not) OR, . , , , . , , , not (!).

:

The more approaches are part of a condition or expression, the more difficult it becomes. But the more often you formulate difficult conditions, the better you will cope with them. To train, you can always break the conditions into several lines and assign labels (variables) to your part:

$status = $getadstatus['ad_status'];
$statusIs1or4 = $status==1 || $status==4;
$statusIsNot1or4 = !$statusIs1or4;
if ($statusIsNot1or4) return -3;

For production code, this may be excessive, but, as always, authors choose how to write something, you can do whatever the language allows.

0
source

All Articles