I am having trouble with my IF statement, it is always TRUE although this is incorrect. I'm using an OR operator as there are two possible scenarios I want to capture in the IF statement.
The array string ad_status is "1" but using the below -3 is returned, I'm expecting the IF to be FALSE. If I remove the OR and second statement from the IF, the result of the IF is correct.
What have I done wrong? Thanks.
if(($getadstatus['ad_status'] != "1" || $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
Additional:
What I want to do is exit the function (not seen in full here) if ad_status does not equal 1 or 4. If it equals any other value other than 1 or 4, the IF statement should return TRUE and exit.
ad_status could be any value from 0 to 4.
What you are saying is that any value that is not 1 OR is not 4 should return true.
For '1' you get the statement
if( 1 != 1 || 1 != 4)
which translates to
if( false || true )
which is ofcourse true.
What you need is:
if(!($value == 1 || $value==4))
which is the same as (de Morgan's law)
if($value != 1 && $value != 4)
You check:
ad_status != 1 -> FALSE
ad_status != 4 -> TRUE
if (FALSE OR TRUE) is always TRUE.
To be what you expected, replace OR with AND:
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
It will always be true as any value can't be both '1' and '4' at the same time.
You should use && operator because use !=. If you want to use || you could write like this:
if (!($getadstatus['ad_status'] == "1" || $getadstatus['ad_status'] == "4"))
You want to use &&
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
I personally prefer in_array instead of OR in IF statemements. Eg:
$array = array(1,4);
if (!in_array($getadstatus['ad_status'], $array)) {
// do whatever
}
There are no errors there.
If ad_status == 1 then your second condition will get you into the If
$getadstatus['ad_status'] != "4"
is true therefore you will get return -3;
If i got what you want you should use AND
if ( $a!= 1 AND $a!= 4 )
humm, ok I think I see. I'm attempting to be too clever. I want to use a single IF statement to check for two non related conditions. If ad_status does not equal 1 OR 4, return -3 and exit the function.
Okay, no problem, that can be expressed, just formulate like you write:
$status = $getadstatus['ad_status']; // assign a variable as it makes things easier to read.
if ( !( $status==1 || $status==4 ) )
{
return -3;
}
So the ! (not) should be on the whole OR comparison as you wrote in your sentence. That's probably in code what you had originally in mind. But as the order is important, the other part of your condition needs to be inside brackets to be calculated first, before using the not (!) operator.
Added:
The more sub-conditions are part of a condition or expression, the more complex it gets. But the more often you formulate complex conditions the better you will get with them. To train, you can always split conditions over multiple lines and assign labels (variables) to their part:
$status = $getadstatus['ad_status'];
$statusIs1or4 = $status==1 || $status==4;
$statusIsNot1or4 = !$statusIs1or4;
if ($statusIsNot1or4) return -3;
For production code this might be overuse, but as it's always the authors choice how to write something, you can do whatever the language allows.
Related
I want to check whether the length of $a is 0 or if the length is not 0 then check if it is a numeric value in single IF statement in PHP. I tried this but not working
$a = '23bc';
if((strlen($a)===0 || (strlen($a)>0 && ctype_digit($a))) )
{
echo 'Good to Go';
}
else
{
echo 'Bad to Go';
}
I do not want to apply nested conditions here. Is it possible to do it in single IF statement?
I found this question here but this does not answers what I am asking for && (AND) and || (OR) in IF statements
It would be nice to know what your script is trying to achieve beyond using a one-liner in an if conditional concerning an empty string or a numeric string. With cytpe_digit() every character must evaluate as a number to qualify as a numeric string. You get a false result with '23bc' because of the 'bc' portion.
One of the problematic aspects with the script is that one don't know which condition results in a true. One or the other conditions could be true or they could both be false.
See demo: http://3v4l.org/8Pchk.
You could rewrite the code making use of a ternary expression to have a one liner which eliminates the if-else construct, as follows:
<?php
$a = '23bc';
if( strlen( $a ) != 0) {
echo ctype_digit( $a )? "Good to Go\n" : "Bad to Go\n";
}
The following may be more in line with what you're asking. Here's the ultimate one-liner:
<?php
echo ( !strlen($a) || ctype_digit($a) )? "Good to Go\n" : "Bad to Go\n";
Because of the strictness of the identity operator === if $a is null, then you you'll see "Bad to Go. You may either test for equality strlen($a) == 0 or you can be more succinct by using the ! operator (boolean NOT). See demo: http://3v4l.org/7cfV0
I've noticed in my dealings with PHP & javascript, still learning btw, that the following seems to produce the same results.
if( ( $A==0 ) && ( $B==0 ) ){}
if( $A==0 && $B==0 ){}
What is the proper term for this in programming so I can learn more about it.
Parenthesis determine the order in which comparisons are made. Your example is a pretty simple one that doesn't need parenthesis at all, but look at something like this
if ($a == 0 || $b == 0 && $c == 0 || $dd == 0)
This is actually equivalent to
if ($a == 0 || ($b == 0 && $c == 0) || $dd == 0)
because && is evaluated first in PHP as it has a higher precedence than the ||
IN most cases, when you have complex conditionals, you want to make sure to use parenthesis, if not to get the order of operations right, then at least to make it clear to the code reader what you are trying to do.
The term is called operator precedence.
http://php.net/manual/en/language.operators.precedence.php
Due to Operator Precedence rules, the two lines are the same.
The == takes precedence over the && operator.
Extra (unnecessary) parentheses are sometimes used to make a statement clearer, or sometimes used because the author doesn't know the precedence, or due to voodoo programming
Order of operations, as #asawyer said.
Source: http://en.wikipedia.org/wiki/Order_of_operations#Programming_languages
IN your specific example there is no difference, however, there are cases when paranthethis makes a big difference.
Example:
if(a == 0 && (b == 0 || c == 0)) {
// do something
}
If you noticed, in this case only 2 out of 3 variables have to be 0 in o
What you are seeing is extra parentheses based on the Order of Operations. Parentheses are used to override the usual order. To take a mathematical example:
7 + 2 * 4 + 3
Will first have 2 * 4 evaluated to 8, giving:
7 + 8 + 3
Multiplication has a higher precedence than addition, so it is evaluated first. You can override that by using parentheses:
(7 + 2) * 4 + 3
In this case, the first operation to be evauluated is the addition, giving:
9 * 4 + 3
The same principle is in effect for bit-wise, boolean, and comparison operators in an if statement. Comparison operations have a higher precedence than boolean operators, so if you have, for example:
1 == 4 || 7 > 3
the comparisons will be evaluated first, giving
false || true
A lot of programmers are used to programming "safely", by putting parentheses around the comparisons:
(1 == 4) || (7 > 3)
In a way, this makes the code look a bit cleaner and guarantees that the comparison will be evaluated first.
It is called operator precedence
if( ( $A==0 ) && ( $B==0 ) ){}
if( $A==0 && $B==0 ){}
In your example both lines evaludate the same. Basically things in parenthesis get processed first.This can be noticed better when you have something like:
if( ( $A==0 && $C!= 1) && ( $B==0 || $D >0) ){}
In the above example. The conditions inside ( $A==0 && $C!= 1) and ( $B==0 || $D >0) are first evalulated, and then results are evaluated against the main && sign.
So supposing:
( $A==0 && $C!= 1) evaluated to TRUE
and
( $B==0 || $D >0) evaluated to FALSE
The condition
if( ( $A==0 && $C!= 1) && ( $B==0 || $D >0) ){}
becomes
if( ( TRUE) && ( FALSE) ){}
which naturally evaluates to FALSE in the end
the brackets are used when dealing with multiple && and || also known as and and or. It's a lot like math where if you have the equation 2+4*2=10 this is because you do the multiplication before the addition. where as (2+4)*2=12 because the brackets make you do the addition.
So in a nutshell brackets have the highest precedence in the if operation.
I hope that makes this clearer for you. have a nice day.
You should combine the two arguments if you want to check both conditions simulataneously, but by separating them by using two different parentheses sets you are checking each condition for each loop inside the if statement.
This issue is simple, but I am not sure what is the best approach to get around it.
If the variable contains a number, how can I make sure that the if statement only returns true if indeed the $some_var is one?
you need to use 3 equals
if($some_var ===1){
here is more info http://php.net/manual/en/language.operators.comparison.php
The number 1 is a shortcut for "true". In order to specify that it must actually be true, you want to use a triple equals operator. This makes sure it matches both value and type (1 and integer, respectively).
$some_var = 1;
$other_var = "1";
$some_var === 1; // True
$other_var === 1; // False
if($some_var === 1) //checks also type
Ideally, you should be using ===, but the downside of that is its going to check for both value and type. This should be fine if you want to check for 1 as an integer. But since 1 could also be a string value (data submitted by forms are always strings), your === comparison might fail. Try this instead:
if ($my_var == 1 && is_numeric($my_var)) {
echo 'My condition is true. Woo hoo!';
}
Simple but this has always bothered me. Which is the best way to condition statement?
$foo = '1';
if($foo === '1' || $foo === '2' || $foo === '3')
{
// foo matches
}
or
if($foo === '1' || '2' || '3')
{
// foo matches
}
Which step works and is better. is there a better solution?
The second version will always evaluate to true.
If you want to compact the comparison against multiple alternatives then use:
if (in_array($foo, array('1', '2', '3') )) {
If you want to closely match the exact comparison === then you would however need:
if (is_string($foo) && in_array($foo, array(...))) {
$foo = 1;
if(in_array($foo, array(1, 2, 3))){
//foo matches
}
This is an alternative:
if($foo>0 && $foo<4){
}
Second if statement won't work. PHP doesn't work like that. Any number other than 0 (including negatives) evaluates to true when alone in an if statement. This is why you can do something like if(count($array)) without specifying that count($array) must be greater than 0.
Would be the same as if you had said:
if($foo === 1)
{}
elseif(2) //This will always trigger if $foo !== 1.
{}
elseif(3) //This will never trigger because of the last one
{}
Each condition is it's own self contained condition. Instead of reading it as just "or" or "and" read it as "or if" and "and if". So if $foo is 1 or if 2 or if 3 instead of if $foo is 1 or 2 or 3
If it's just numeric, then amosrivera's solution is the best. If it's for other types of data, then webarto/mario have a good solution.
We are trying to use the below piece of code
if (($_GET['1'] != "1") || ($_GET['1'] != "2")) {
When we try this no matter what value the variable has it will evaluate as true even when data is entered that is false. When we use
if (($_GET['1'] == "1") || ($_GET['1'] == "2")) {
and put in data that will make it return false it works correctly. We have reversed the way that the if statement goes just so we can get this working but i would like to know why this doesnt work, if it is something im doing wrong or a limitation within php with the or and the not equal operators
Thanks
Your first test is saying this:
If $_GET['1'] is anything other than "1" OR $_GET['1'] is anything other than "2"
The expression will always pass: If it equals 1 it will pass the != '2' test on the second half of your if statement. If it equals 2 it will pass the != '1' test on the first half, and never make it to the second half of the test.
The second test simply says:
If $_GET['1'] equals "1" OR $_GET['1'] equals "2" then the expression should pass
You probably want this expression, which will pass only if neither parameter holds the correct value:
if(($_GET['1'] != '1') && ($_GET['1'] != '2'))
The expression below will always evaluate to TRUE, because either x is not 1 or x is not 2. There is no way that x can equal both 1 and 2 at the same time!
($x != 1) || ($x != 2)
The opposite of
($x == 1) || ($x == 2)
is
($x != 1) && ($x != 2)
Note that you have to change the || to a &&.
Try:
if (($_GET['1'] != "1") && ($_GET['2'] != "2")) {
If you use != in both statements, then you need to use && instead of || to make sure both statements get evaluated.
Essentially, using || means that the first statement gets evaluated and if it is false, then PHP will ignore the second statement because you are using OR. But if you use &&, then PHP will be sure to evaluate both != statements.
if your code is:
if (($_GET['1'] != "1") || ($_GET['2'] != "2")) {
any value or even null value can enter this condition. you can change || to && meaning any string which is not equal to "1" and "2" can enter you condition
Without knowing the intention of the statement, or what input you started with (or how you revised it), I can't say for certain what the issue is.
That said, the first statement will only evaluate to FALSE if $_GET['1'] is equal to 1 and $_GET['2'] is equal to 2.
The second statement will only evaluate to FALSE if $_GET['1'] is not equal to 1 and $_GET['2'] is not equal to 2.
I'm guessing what you wanted on your first statement was
if (($_GET['1'] != "1") && ($_GET['2'] != "2")) {
which evaluates to FALSE unless $_GET['1'] is equal to 1 and $_GET['2'] is equal to 2.