Comparing equality to one of multiple values [duplicate] - php

This question already has answers here:
PHP If Statement with Multiple Conditions
(11 answers)
Closed 9 years ago.
I'm passing values on a url to a page on my site. So when a user clicks a link different values will pass to the new page depending on which link they click. I'm using a conditional on the second page to vary the code that gets run depending on the value in $_GET.
Unfortunately, for reasons unknown to me the conditionals don't seem to be working properly. In the if statements I'm using || because there are multiple passed values that need to trigger the same code on the second page (they need to be named differently because they also all trigger unique code).
It seems rather simple, I start with:
if($_GET['id']=('x' || 'y' || 'z')) {
block of code
}elseif($_GET['id']=('a' || 'b' || 'c')) {
block of code
}else{
block of code
}
I have printed out the values of the $_GET['id'] to check that the correct value is being passed from the first page to the second based on the link clicked. This is working properly. Every link I click prints the expected value. The odd thing is I echo'd these values both within the first conditional and above it. It printed in both cases, even when it printed a value that shouldn't have triggered that conditional. Any ideas?

The syntax you're using for checking if $_GET['id'] is one of the valid values in the set is wrong.
I think you mean to be doing something more like this:
<?php
if (in_array($_GET['id'], array('x', 'y', 'z') {
/* block 1*/
}
else if (in_array($_GET['id'], array('a', 'b', 'c')) {
/* block 2 */
}
else {
/* block 3 */
}
Some further information on the code you did write:
It's passing because the syntax is valid, but not for what you want to do.
Essentially you're saying "Assign $_GET['id'] to the first truthy value of 'a', 'b', or 'c'." The problem there is, all strings (unless they are "0") are evaluated as true.
Furthermore, the single equals symbol (=) assigns the value to the variable and evaluates as true (the assignment was successful). So you're always setting $_GET['id'] to the first string in ('a' || 'b' || 'c'). Therefore, you're assigning $_GET['id'] and it's evaluating to true so the first if condition is always met.

if($_GET['id'] == 'x' || $_GET['id'] == 'y' || $_GET['id'] == 'z') {
block of code
}elseif($_GET['id'] == 'a' || $_GET['id'] == 'b' || $_GET['id'] == 'c') {
block of code
}else{
block of code
}

I think you can also use switch statement. Like the following
$value = 'x'; // $_GET['id']
switch($value) {
//matches if one or more case is met
case 'x':
case 'y':
case 'z':
echo 'i am x, y or z';//here your block code
break;
//matches if one or more case is met
case 'a':
case 'b':
case 'c':
echo 'i am x, y or z';//here your block code
break;
default:
echo 'I have no value';
}

Related

multiple !isset() with OR conditions in php

if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
My Other Tries:
(!isset($_GET['new_quiz'] || $_GET['view_quiz'] || $_GET['alter_quiz']))
( ! ) Fatal error: Cannot use isset() on the result of an expression
(you can use "null !== expression" instead) in
C:\wamp\www\jainvidhya\subdomains\teacher\quiz.php on line 94
(!isset($_GET['new_quiz'],$_GET['view_quiz'],$_GET['alter_quiz']))
NO
You may find than inverting the logic makes the code easier to read, I also like to have a more positive idea of conditions as it can read easier (rather than several nots means no).
So this says if anyone of the items isset() then the answer is Yes...
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo "Yes";
}
else{ echo "No"; }
Note that I've changed the Yes and No branches of the if around.
You are probably looking for
if(!isset($_GET['new_quiz']) && !isset($_GET['view_quiz']) && !isset($_GET['alter_quiz'])){
echo "No";
}
else {
echo "Yes";
}
which will print Yes if none of new_quiz, view_quiz and alter_quiz are present in the URL. If this is not your desired outcome, please elaborate on your problem.
#paran you need to set a value for view_quiz=yes for example
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
and the url
index.php?new_quiz=yes
index.php?view_quiz=yes
index.php?alter_quiz=yes
All Will return true
isset()allows multiple params. If at least 1 param does not exist (or is NULL), isset() returns false. If all params exist, isset() return true.
So try this:
if( !isset( $_GET['new_quiz'], $_GET['view_quiz'], $_GET['alter_quiz']) ) {
First, to answer your question:
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
This is becaue this
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
checks if either one of your parameter is not set, which will always be the case as long as you are not setting all three parameter simultaneously like this:
index.php?alter_quiz&view_quiz&new_quiz
As #nigel-ren stated, you may wan't to change that logic to
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo 'Yes';
which checks if at least one parameter is set.
If you wan't to check if there is only one of the three parameters set, you would have to work with XOR (which is slightly more complicated)
$a = isset($_GET['new_quiz']);
$b = isset($_GET['view_quiz']);
$c = isset($_GET['alter_quiz']);
if( ($a xor $b xor $c) && !($a && $b && $c) ){
echo 'Yes';
(based on this answer: XOR of three values)
which would return true if one and only one of the three parameters is set.
But - and this is just an assumption, please correct me if I'm wrong - I think what you are trying to achieve are three different pages (one for creating a quiz, one for viewing it and one for editing it). Therefore, you will likely run into a problem with your current setup. For example: What would happen if a user calls the page with multiple parameters, like
index.php?alter_quiz&view_quiz
Would you show both pages? Would you ignore one parameter? I would recommend to work with a single parameter to avoid this problem in the first place. For example site which can take the values alter_quiz, view_quiz or new_quiz. E.g.:
index.php?site=alter_quiz
Then you can work like this:
// check if site is set before getting its value
$site = array_key_exists( 'site', $_GET ) ? $_GET['site'] : NULL;
// if it's not set e.g. index.php without parameters is called
if( is_null($site) ){
// show the start page or something
}else{
$allowed_sites = ['new_quiz', 'view_quiz', 'alter_quiz'];
// never trust user input, check if
// site is an allowed value
if( !in_array($site, $allowed_sites, true) ){
die('404 - This site is no available');
}
// here you can do whatever your site should do
// e.g. include another php script which contains
// your site
include('path/to/your/site-' . $site . '.php');
// or echo yes
echo 'Yes';
}

OR statement returning wrong number

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;

Not operator with multiple or operator

I am confuse with bellow code:
Fist code that is not working:
if ($_SESSION['userType'] != 'A' || $_SESSION['userType'] != 'S')
{
redirect('dashboard.php');
}
Second code that is working:
if (!($_SESSION['userType'] == 'A' || $_SESSION['userType'] == 'S'))
{
redirect('dashboard.php');
}
What is difference between both code?
I know you already have six answers to your question, but none of them uses plain English, so I'll make an attempt myself as well.
Let's look at this code step by step, splitting it up into smaller portions, and explaining each step exactly.
Code that isn't working
First you have this row:
if ($_SESSION['userType'] != 'A' || $_SESSION['userType'] != 'S')
Instead of looking at the full if clause already, let's divide it into two parts:
if ($_SESSION['userType'] != 'A')
if ($_SESSION['userType'] != 'S')
The first part will trigger any time that $_SESSION['userType'] is any value other than A.
The second part will trigger any time that $_SESSION['userType'] is any value other than S.
Now, you've joined them both together with an "or" operator, so that it's enough that one of them is true for the if clause to trigger. Let's see what happens when we try it out.
We set $_SESSION['userType'] to 'B' and go into the if clause. The first thing that happens is that PHP looks at the first part, if ($_SESSION['userType'] != 'A'), and finds that 'B' != 'A'. It doesn't need to go to the second part, because it already found that one of the parts of the if statement is true, and so it decides that the full if statement must also be true.
We set $_SESSION['userType'] to 'A' and go into the if clause. The first thing that happens is that PHP looks at the first part, if ($_SESSION['userType'] != 'A'), and finds that 'A' == 'A', so the first part is false. It then goes on to the second part, which is if ($_SESSION['userType'] != 'S'), and finds that 'A' != 'S'. Since this means that one of the parts of the if statement is true, it again decides that the full if statement must also be true.
Now notice what this means. Even if you send an 'A' to the if clause, it will still trigger because of the second part. And if you were to send an 'S', it will trigger because of the first part. So essentially, the full first if statement will trigger regardless of what $_SESSION['userType'] is set to. It's a tautology - it's always true.
Code that is working
This is your full if statement:
if (!($_SESSION['userType'] == 'A' || $_SESSION['userType'] == 'S'))
Let's ignore the ! for now, and divide it into the two parts of the or operator.
if ($_SESSION['userType'] == 'A')
if ($_SESSION['userType'] == 'S')
Notice that this is the logical opposite of the code you had that didn't work. The first row means "only accept an 'A'" and the second means "only accept an 'S'". So this code will trigger only if you give it either an 'A', or an 'S'.
Now, what happens if you put an ! in front of the whole thing, like you did?
The ! operator simply reverses whatever it is put in front of. So this changes the meaning from "either A or S" to "neither A nor S".
Summary
Your first example comes down to "any value whatsoever".
Your second example comes down to "any value, but not A, and also not S".
If you want to learn more of basic logic, I suggest looking at De Morgan's laws, as you were linked to in an above comment. This will give you an understanding of how and and or fits together.
Not...quite.
If I remember boolean logic correctly, the fault lies in order of operations.
if ($_SESSION['userType'] != 'A' || $_SESSION['userType'] != 'S') {
if userType equals A, this will not work...since the first operation is to check that it is not equal to A and ORs are left to right...so if the first is not true, the entire statement is false.
Your second approach translates to:
if (!($_SESSION['userType'] == 'A' || $_SESSION['userType'] == 'S'))
{
redirect('dashboard.php');
}
IF NOT userType equals A OR userType equals S which is why it works as you desire it to.
Try
if ($_SESSION['userType'] != 'A' && $_SESSION['userType'] != 'S')) {
which means IF userType is not A and userType is not S
I think that will give you what you are probably looking for. IE Only do what is in the loop if the userType is neither A, nor S.
if ($_SESSION['userType'] != 'A' || $_SESSION['userType'] != 'S') {
is more or less equivalent to
if (!($_SESSION['userType'] == 'A' && $_SESSION['userType'] == 'S')) {
first code that is not working
if ($_SESSION['userType'] != 'A' || $_SESSION['userType'] != 'S')
{
redirect('dashboard.php');
}
lets simplyfy it as under:
if (true || true) //the condition will be true or vice versa
{
redirect('dashboard.php');
}
Second code that is working:
if (!($_SESSION['userType'] == 'A' || $_SESSION['userType'] == 'S'))
{
redirect('dashboard.php');
}
and the simplified version:
if (!(true || true)) same as if (!(true)) //i.e. false or vice versa
{
redirect('dashboard.php');
}
so basically one is true and the other is false or vice versa so thats why they are acting diffrenetly.

PHP Multiple condition if statement returning nothing

I have been trying to figure this out for weeks, it is a simple statement yet it never executes the if statement. I'm echoing the variables to the screen so I know they exist and each condition is true, but the echo "something" never executes.
if ($db_a==$session_a && $db_b==$session_b && $dbfreq_b=="1")
{
echo "something";
}
I thought it was just the brackets as I had this originally:
if (($db_a==$session_a) && ($db_b==$session_b) && ($dbfreq_b=="1"))
I am comparing variables stored in a MYSQL database with session variables.
If I use Var_dump the db variables are null, yet they echo the expected string value to the screen.
$db_a="username";
$session_a="username";
$db_b=="keyword string"; -mostly one word but could be multiple
$session_b=="keyword string";
$dbfreq_b="1"; - This is the frequency that the keyword appears in the MYSQL database
using vardump $db_a and $db_b are NULL yet they echo what I am expecting to see to the browser.
Hopefully this explains things a bit more?
Thank you for the very prompt help!!
If as you say $db_a = $session_a AND $db_b = $session_b AND $dbfreq_b = 1 then it's impossible that condition returns false.
Please check your code again (all 5 variables) and make sure ALL of the conditions are met.
You could just split your single IF into three separate conditions so that you know which one returns false.
if ($db_a == $session_a) {
echo "first OK\n;"
}
if ($db_b == $session_b) {
echo "second OK\n";
}
if ($dbfreq_b == "1") {
echo "third OK";
}
Could you add the values of your variables to your question?

Explanation for very odd php function return

So my code in the past needed a variable to run through 2 functions and then return the value as such.
function 1($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
// pass the return to next function
function 2($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
On the next check it returns a message to the user as such:
if($variable == -1) // display message
if($variable == -2) // display message
if($variable == true) // display message
Now, per requirement of work the variable must go through a 3rd function check still returning a -1, -2 or true and then go onto the final if statements for display.
Now this is where it gets odd. If I keep it at 2 functions the if statements work, however if I run it through the 3rd check function I need to format my if's like this in order to correctly check the return:
if($variable === -1) // display message
if($variable === -2) // display message
if($variable === true) // display message
Notice I have to add the 3rd '=' symbol. I just can't figure out why this is happening. Is this normal by some PHP law I don't know about or is this a bug?
This is not odd behavior, it's very natural for PHP.
Following expression:
if ($variable == true) {
}
means that PHP will cast left operand to less pretensive type(in this case BOOLEAN) and do comparison after this. Which obviously will result in TRUE if $variable value is not 0 or FALSE or NULL or ''
In second case i.e. === there is strict check value and type of both operands are compared.
The triple equals sign (===) only returns true if the two objects being compared are identical (of the same type and value), not just equal.
For example:
$a = 1;
$b = "1";
echo $a == $b; // True
echo $a === $b; // False
Your code does not show how you call the functions and store returns, there may be a problem. Plus, I suppose you called function 1 and 2 only for illustration because as you know you cant start name of the function with a number.
=== is 'equals exactly' (value and type). Often used for logical tests, because sometimes you need to distinguish 0 from false and 1 from true.

Categories