OR statement returning wrong number - php

If i put 1 or 2 into this it will return 4. Why is this?I'm more used to python stuff so sorry if this is rather basic.
e = 1;
f=0;
if(e==1){f=1;}
if(e==2){f=2;}
if(e== 3 or 4){f=4;}
echo f;

Try replacing :
if(e== 3 or 4){f=4;}
with
if(e == 3 or e == 4){ f=4; }
The value 4 is considered to be TRUE by the language. In your code, 1 == 3 is FALSE, so the if statement is looking at (FALSE or TRUE) which is equals TRUE, so f is set to 4.
Have a look at this link re: PHP Booleans

For your or statement, this is what you want:
if ( ($e == 3) || ($e == 4) ) {
$f=4;
}

The next statement is always going to be true
if(e== 3 or 4)

If you take a look at booleans, you'll see that pretty much everything is equals to true in php (except for those values stated in that same page). So what you really have is something like this:
if($e==3 or true)
And since anything or true is always true, you get that (weird, but not unexpected) result.
In case you want to check if $e is equals to 3 or 4, do it like so:
if($e==3 || $e==4){
Note that since these are not if..else statements, every condition is being checked. Take a look at the expanded version:
if($e==1){
$f=1;
}
if($e==2){
$f=2;
}
if($e==3 or 4){
$f=4;
}
This /\ is different from
if($e==1){
$f=1;
}elseif($e==2){
$f=2;
}elseif($e==3 or 4){
$f=4;
}
Since the latter only checks every condition in case none of the previous fit.
Another side note.. since you like python, that code could be converted into this single line:
$f = ($e==3 || $e==4) ? 4 : $e;

Related

PHP - if single value equals multiple options

So I understand this - and comparing/checking values. However, I was messing about and noticed the outcome for all my tests were the same - some of which I was taught (a) didn't work or (b) was incorrect.
Note, I'm running PHP7. Okay, to my point. I was able to achieve the same outcome checking if a single value equals one of multiple options...
These work...why? Def not the way I learned.
if ($status == 'in-progress' || 'in-review')
// and even
if ($status == ('in-progress' || 'in-review')) // kind of similar to ASP.NET Razor
I normally would repeat the check, like so: if($stat == 'a' || $stat == 'b') or even in_array() which is essentially the same thing.
Is the first examples, correct? If not, why is it working? Or is this something frowned upon and not practiced - or maybe even something new?
First off to make it clear == has a higher precedence than ||. This means your two if statements look like this:
if (($status == 'in-progress') || 'in-review')
if ($status == ('in-progress' || 'in-review'))
Now for your first if statement regardless what value $status has and what the outcome of ($status == 'in-progress') is, since you have an OR in it and after it 'in-review' your if statement will always be true, since a non empty string is a truthy value.
For your second statement, this part ('in-progress' || 'in-review') comes literally down to TRUE || TRUE, which evaluates to TRUE. Now $status just needs to hold a truthy value and the if statement will be true.
No, that code will never work. || has a lower precedence than ==, so you're comparing $status against the first value, then boolean || "or" the other value
if (($status == 'foo') || ('bar'))
You have to compare the values individually:
if (($status == 'foo') || ($status == 'bar'))
And this gets tedious for many values. A quick hack is to use an array:
if (in_array($status, array('foo', 'bar', 'baz', 'qux', 'etc...')))

check compound condition using OR and AND in php

I want to check the condition either of one among $flag1==1 or $flag2==2 or $flag3==3 along with that $flag4 == 4 is true then I want to execute a statement.This is not working in php.I tried:
if (($flag1==1 or $flag2 == 2 or $flag3 ==3) and $flag == 4)
{
$variable1 ='Change in Asset and Transformation Approach';
echo $variable1;
}
I think your problem is a typo. You mentioned you wanted $flag4 to equal 4. But you are checking the value of $flag.
if (($flag1 == 1 or $flag2 == 2 or $flag3 ==3) and $flag4 == 4) { // <-- notice $flag4
$variable1 ='Change in Asset and Transformation Approach';
echo $variable1;
}
Working Codepad.

PHP If a variable equals this or this

I have this if statement in my PHP:
if($_SESSION['usrName']!='test1'){
header('location:login.php');
}
But i want it to be something like this:
if($_SESSION['usrName']!='test1' or 'user'){
header('location:login.php');
}
But i cant figure out how to do it in PHP code. I have tried this:
if($_SESSION['usrName']!='test1','user'){
header('location:login.php');
}
And this:
if(($_SESSION['usrName']!='test1')||($_SESSION['usrName']!='user')){
header('location:login.php');
}
Can anybody help please?
You have to replace the || with &&. Because you only want to redirect when both conditions are true.
if(($_SESSION['usrName']!='test1') && ($_SESSION['usrName']!='user')){
header('location:login.php');
}
if (!in_array($_SESSION['usrName'], array('test1', 'user')) {
header('location:login.php');
}
This checks if variable $_SESSION['usrName'] is not in list of strings to simplify additional allowed user.
As others have said, you need to be careful with your boolean logic - (NOT X) || (NOT Y) is equivalent to NOT (X AND Y), whereas what you want is NOT (X OR Y) which is equivalent to (NOT X) AND (NOT Y).
For this particular situation, there are also a couple of other options, although none as neat as the invalid syntaxes you tried.
First, there is in_array(), which is easy to read, but not very efficient if you use it a lot with long lists (for a simple case like this, it's not worth worrying about performance, though):
$allowed_users = array('test1', 'user');
if ( ! in_array($_SESSION['usrName'], $allowed_users ) { ... }
Or, you can build a hash with the usernames as keys; this is more efficient as the list grows, because PHP can check for a key without looping through the whole list:
$allowed_users = array('test1' => true, 'user' => true);
if ( ! array_key_exists($_SESSION['usrName'], $allowed_users) ) { ... }
// Or, if you don't mind PHP raising a few notices about accessing undefined keys
if ( ! $allowed_user[ $_SESSION['usrName'] ] ) { ... }
Finally, you can use a switch statement, with the labels falling through, and a default case acting as the "else":
switch ( $_SESSION['usrName'] )
{
case 'test1':
case 'user':
// These users are allowed :)
break;
default:
header('location:login.php');
}
Which, if any, of these you choose to use will depend on how you expect the code to grow in future, but they're useful tricks to know.
Your last attempt is almost correct.
However...
if (var != something || var != something-else)
...will always be true, because one of those conditions will always match. Even if it's equal to one side, it won't be equal to the other.
When you're testing two negatives like that, you need to use AND (&&) instead of OR (||).
if (($_SESSION['usrName']!='test1') && ($_SESSION['usrName']!='user'))
This will match if it's not equal to one, and also not equal to the other.
Currently, you're checking if either one of conditions are true. The last condition will evaluate to true if either one of the conditions are correct. I assume you're trying to check if both the the conditions are true. In that case, you'll need && instead of ||.
Try:
if( ($_SESSION['usrName'] != 'test1') && ($_SESSION['usrName'] != 'user') ) {
header('location:login.php');
}
You need to do something like:
if($_SESSION['usrName'] != 'test1' and $_SESSION['usrName'] != 'user'){
header('location:login.php');
}
The first attempt of yours is equivalent to:
if(($_SESSION['usrName']!='test1') or 'user'){
header('location:login.php');
}
Second seems like invalid syntax
Third is almost right, you just need to replace || with and or &&, as anything will be unequal to either 'user' or 'test1'

PHP: using if when the second condition might not be set

A pretty simple question, I am wondering how php handles the use of IF and AND.
Say i have the following php code:
if ((pony) && (pony == 2)) {
/* do something */
}
if pony is equal to 0, would the code still check if pony is equal to 2 or would it stop there?
No. The boolean operators exhibit short-circuit behavior. In other words, PHP stops evaluating as soon as it knows the result of the entire expression.
See the PHP docs on Logical Operators.
#Jonathon Reinhart is correct, while at the same time you must recognize that you are NOT required to create variables before use.
With that being said this will work:
if ($pony && $pony == 2) {
/* do something */
}
Although, using strict errors in PHP you would need to ensure that (in your case) the variable pony is defined using isset().
if (isset($pony) && $pony == 2) {
/* do something */
}
First, use $ to define variables..
$pony = 0;
if (($pony) && ($pony == 2)) {
echo "yeah";
}
/* false */
The value will be true, if you change the value of $pony = 2;
Logically, nothing was tested during the first condition, its not even a condition.
if($pony){
}
If you change your condition to... where $pony must be 0 and 2 at the same time is impossible
if (($pony == 0) && ($pony == 2)) {
echo "yeah";
}
If you are trying to check if $pony has a value, see Samuel Cook's answer, isset
if (isset($pony) && $pony == 2) {
/* do something */
}
/* does $pony has a value/initiated AND its value must be 2 */

PHP operators if statement 'and' and 'or'

I have an if statement that I want to control with having one field needing input and they have to pick one of the other 2 choices.
if(test1 && test || test3){
//Something here
}
Should I do it like this:
if(test1 && (test2 || test3)){
//do stuff
}
How would I go about doing this. I can't wrap my head around the logic...
if ($requiredField && ($optional1 || $optional2)) {
/* Do something */
}
For the /* Do something */ bit of code to be executed, the if statement has to evaluate to TRUE.
This means, that $requiredField must be TRUE, and so must be ($optional1 || $optional2).
For $requiredField to be TRUE, it just needs to be filled in - and for the second part: ($optional1 || $optional2) either optional1 or optional2 would do it.
Edit:
After rereading the question, it seems that I might have misunderstood you. If the user must enter one specific piece of information, and must choose only one (not both) out of two options - then the following should be used.
if ($requiredField && ($optional1 ^ $optional2)) {
/* Do something */
}
This means that $optional1 or $optional2 must be filled out - but not both of them.
From the sound of it, you want the latter:
if ($test1 && ($test2 || $test3)){
//do stuff
}
Think of it as two conditions needing to be met. This gives you those two conditions. The second condition just happens to be another condition. The first option you posted, however, is quite the opposite as it can allow execution if just $test3 is true
test1 && (test2 || test3) is very easy to understand from the first place - Choose test1 && (test2 || test3) means one the last two. Very clear.
test1 && test || test3 - doesn't seem to be correct:
test1 = false
test2 = false
test3 = true
false && false || true = true
doesn't actually fit your criteria.
... they have to pick one of the other 2 choices
I'm just throwing a guess out here. If you really want to ensure that one, but only one of the two other options are selected, then you need xor:
if ($required AND ($and_either XOR $or_other)) {
You can have 'nested' if statements withing a single if statement, with additional parenthesis.
if(test1 && (test2 || test3)){
//do stuff
}
Your logic is right but your sintax isnt, you should compare the values of the variables as show, or simply ignore them as saying you are trying to compare them as they are TRUE.
$test1=true;
$test2=true;
$test3=false;
if($test1==true && ($test2==true || $test3==true){ echo "YES";}
This will output YES.

Categories