If statement with && and multiple OR conditions in PHP - php

I'm having trouble trying to make the statement below work the way I want it to.
I am trying to display an error message for an order form if at least one text field is not filled out. Below is a snippet of my PHP code. The 'cookieGiftBox' is the name of a checkbox that users can select and if it is selected, they must enter an amount of cookies under their desired flavors in the text fields provided. How can I display an error message to display when the checkbox IS selected but NO text fields have been filled out?
<?php
if (isset($_POST['cookieGiftBox'])
&& (!isset($_POST['sugar'])
|| ($_POST['chocolateChip'])
|| ($_POST['chocolateChipPecan'])
|| ($_POST['whiteChocolateRaspberry'])
|| ($_POST['peanutChocolateChip'])
|| ($_POST['peanutButter'])
|| ($_POST['tripleChocolateChip'])
|| ($_POST['whiteChocolateChip'])
|| ($_POST['oatmealRaisin'])
|| ($_POST['cinnamonSpice'])
|| ($_POST['candyChocolateChip'])
|| ($_POST['butterscotchToffee'])
|| ($_POST['snickerdoodle']))) {
$error.="<br />Please enter an Amount for Cookie Flavors";
}
?>

&& takes precedence over ||, thus you would have to use parentheses to get the expected result:
if (isset($_POST['cookieGiftBox']) && (!isset($POST['sugar']) || ...)
Actually, to get check if nothing is selected, you would do something like this:
if checkbox is checked and not (sugar is checked or chocolatechip is checked) or the equivalent:
if checkbox is checked and sugar is not entered and chocolatechip is not entered....
If you want to know more, search for information about Boolean algebra.
Update: In your example and in the correct syntax the sentence I took as an example would like this (for the first sentence, note the not (!) and the parentheses around the fields, not the checkbox):
if (isset($_POST['cookieGiftBox']) &&
!(
isset($_POST['sugar']) ||
isset($_POST['chocolatechip'])
)
) { error ...}
Or the second sentence, which might be easier to understand (note the && instead of ||):
if (isset($_POST['cookieGiftBox']) &&
!isset($_POST['sugar']) &&
!isset($_POST['chocolatechip'])
) { error...}
Using ands makes sure it is only true (and thus showing the error) if none of the sugar, chocolatechips, etc. fields are set when the giftbox checkbox is checked.
So if the checkbox is checked, and no fields are set it looks like this:
(true && !false && !false) which is equivalent to (true && true && true) which is true, so it shows the error.
If the checkbox is checked and sugar is entered it would look like this:
(true && !true && !false), equ. to (true && false && true), equ. to false and thus no error is shown.
If both sugar and chocolatechip are entered also no error will be shown.

I have simillar issue:
I try use:
if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') || ($this->context->controller->php_self != 'product') || ($this->context->controller->php_self != 'index')){ ... }
Thats didn't work, I change it to:
if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') && ($this->context->controller->php_self != 'product') && ($this->context->controller->php_self != 'index')){ ... }
I dont know it is correct?
Edit. This is not correct, but for now i didnt know how to fix it.

Related

full if then statement is not being read php

I have a program that evaluates an if then statement and returns true or false
false = everything is good
true = still need more info
so here is my code
function city_state_zip_requirement($parameters_ar){
//clear requirements if all the address fields are filled and the first and last or company is filled
if (!empty($parameters_ar['Address']) && !empty($parameters_ar['City']) && !empty($parameters_ar['State']) && !empty($parameters_ar['Zip']) && (!empty($paramenters_ar['First'] && !empty($paramenters_ar['Last'])) || !empty($paramenters_ar['Company']))){
return false;
// clear the requirement if the first and last name or company fields are filled and there is no filled field in the address city state or zip column
} elseif ((!empty($parameters_ar['First']) && !empty($parameters_ar['Last']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip'])) || (!empty($parameters_ar['Company']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip']))){
return false;
// clear the requirement if the email address field is filled and the adress fields are either all filled or all empty
} elseif (!empty($parameters_ar['Email_Address']) && empty($parameters_ar['Address']) && empty($parameters_ar['City']) && empty($parameters_ar['State']) && empty($parameters_ar['Zip'])){
return false;
} else {
return true;
}}
all the fields are pulled from a user form that sends data through $_POST
what I am trying to accomplish is if the user enters info into a first (first name) and last (last name) or company field the address fields must be either all filled or all empty (i.e. cannot have only state filled for example)
upon debugging the statement that is evaluating to be true (and therefore returning false) is the second from the top
the:
} elseif ((!empty($parameters_ar['First']) && !empty($parameters_ar['Last']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip'])) || (!empty($parameters_ar['Company']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip']))){
return false;
it doesnt seem to make sense that when a user inputs data into the form php is evaluating that the above statement is true (and therefore returning false) if only parameter_ar['First'] and $parameter_ar['Last'] or $paramenter_ar['Company'] is filled while one of the address fields is filled
Rewrite your code so that it only uses one return statement and make functions to validate your request param array based on the cases you want to evaluate. By breaking your code down into smaller pieces it will be more manageable. For example
function yourFunction($params) {
$needMoreInfo = true;
if (isValidCase1($params) || isValidCase2($params) ... ) {
$needMoreInfo = false;
}
return $needMoreInfo;
}
// define your validation functions here
Edit
The condition you find strange is
(
!empty($parameters_ar['First'])
&& !empty($parameters_ar['Last'])
&& empty($paramenters_ar['Address'])
&& empty($paramenters_ar['City'])
&& empty($paramenters_ar['State'])
&& empty($paramenters_ar['Zip'])
)
||
(
!empty($parameters_ar['Company'])
&& empty($paramenters_ar['Address'])
&& empty($paramenters_ar['City'])
&& empty($paramenters_ar['State'])
&& empty($paramenters_ar['Zip']))
)
Analysing the first part of the logical OR
Not empty: first name, last name
Empty: address, city, state, zip
This condition will evaluate to TRUE if first name and last name are the only fields filled out. Since a "return false" follows, in this case, FALSE is returned.
Read more about logical AND, OR, NOT if still unclear.
It could also be that there is an errore in the HTML form causing a submit different from what you expect bit this can't be determined with the code provided
I couldnt for the life of me figure out why PHP was ignoring the other && in the statements after $parameters_ar['First'] and $parameters_ar['Last'], as it turns out.
I was spelling parameters_ar['Address'] (and the other fields) incorrectly, I was instead spelling it paramenters_ar['Address'] once I fixed the spelling error the issues went away.
I am using Notepad++ and it seems I made the same mistake elsewhere in the file and so the autocomplete feature was bringing up what looked like what I was trying to type but was actually incorrect
This is why php was reading $paramenters_ar['Address'] as empty, because there was no value assigned to them and therefore evaluating to true and therefore returning false.
Thank You

Complicated `if`case, correct?

I'm trying really hard to figure out how to solve this problem. Please be gentle, i'm still learning!
There are four workplaces named: B.Avf, R.Avf, Office and Production. Products is passing theese workplaces. Now i'm building a script that can alert if the same product is passing the same workplace twice. Now, this is the hard part: If the product has passed "B.Avf" it can't pass "R.Avf" whitout an alert, same if the product has passed "R.Avf" it can't pass "B.Avf" whitout and alert. But if the product has passed for ex. "R.Avf" it´s ok to pass "Office" whitout an alert.
This is what i got so far: (It's like example number 5 =)
Maby should i create nested ifstatements instead?
This code will turn true all times!
PHP
if($_SESSION['user']['usr_workplace'] == "R.Avf" ||
$_SESSION['user']['usr_workplace'] == "B.Avf" &&
strpos($history, "R.Avf") !== FALSE ||
strpos($history, "B.Avf") !== FALSE)
Your if condition should be :
//IF this session user workplace is "B.Avf" or "R.Avf"
//AND "B.Avf" or "R.Avf" excist in history, then alert!
if(($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf") && (strpos($history, "R.Avf") !== FALSE || strpos($history, "B.Avf") !== FALSE))
Your if statement can be made a lot simpler by removing one condition and still getting the desired result like so:
if(
($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf")
&&
strpos($history, $_SESSION['user']['usr_workplace']) !== false
)
Notice how you don't need two strpos checks, as the first part of the if statement will only allow the second part to run if it was true.
It would be better to extract this to a method or simplify it further, but for what you've asked this will do :).
This works, it has the right braces:
if($_SESSION['user']['usr_workplace'] == "R.Avf" || ($_SESSION['user']['usr_workplace'] == "B.Avf" && (strpos($history, "R.Avf") !== FALSE || strpos($history, "B.Avf") !== FALSE)))
It checks for r.Avf first, OR and then checks all the conditions within the braces
you should break this if into 2 methods.
one should be called:
isUserSessionRBAvf($_SESSION['user']['usr_workplace'])
the other should check the strpos pos:
isHistoryAvf($history, "R.Avf")
and you would end up with just:
if(isUserSessionRBAvf(...) && isHistoryAvf(...))
this way you have a more readable code and easier to debug.
P.S. consider a different method naming
what you need to do is simply check with session value to $history so you will avoid checking two strpos() where you are doing static string checking:
here you are checking with static string:
strpos($history, "R.Avf") !== FALSE ||
strpos($history, "B.Avf") !== FALSE)
make it dynamic like this:
if($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf" && strpos($history, $_SESSION['user']['usr_workplace']) !== FALSE )

Display HTML if two conditions are true or another two are true or third part of conditions are true

I have php if statement that should display certain HTML code if two conditions are true or another two are true or third part of conditions are true.
I have several arrays - $Options_arr, $MoreOptions_arr, $Special_arr .
To explain in the easiest possible way I want to do this:
if(!empty($Options_arr[0]) && $Options_arr[0]!="") or
(!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="") or
(!empty($Special_arr[0]) && $Special_arr[0]!="")
{?> some HTML here
All help will be appreciated thank you.
empty() already checks for empty string "" so it's shorter:
if(!empty($Options_arr[0]) || !empty($MoreOptions_arr[0]) || !empty($Special_arr[0])) {
//some HTML here
}
BragG, you can use elseif
Like:
if((!empty($Options_arr[0]) && $Options_arr[0]!="") ||
(!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="") ||
(!empty($Special_arr[0]) && $Special_arr[0]!=""))
{
// some html or any code
}
I hope that is what you were looking for..
Feel free to ask any question.
You are just missing some brackets. Also || is more frequently used than OR
if((!empty($Options_arr[0]) && $Options_arr[0]!="") || (!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="") || (!empty($Special_arr[0]) && $Special_arr[0]!="")){
echo '<p>hello</p>';
}
You're basically already there...
if (
(!empty($Options_arr[0]) && $Options_arr[0]!="")
|| (!empty($MoreOptions_arr[0]) && $MoreOptions_arr[0]!="")
|| (!empty($Special_arr[0]) && $Special_arr[0]!="")
){
...do something
Basically you write an if statement that resolves if any of the sub-statements are true by joining the sub-statements together with ORs

Can't view a message through php?

Okay, I have a php code for my mail.php, so that if the current user id doesn't match the to or from id, it will show an error message, but I tested it out and any use can view the message, here's the code :
if (!$mail['to_id'] == $account['id'] && !$mail['from_id'] == $account['id']) {
$system->message(L_ERROR, L_MAIL_ERROR_PERMISSION, './?area=forum&s=mail', L_CONTINUE);
}
But when I added != instead of ==, it shows an error message for everyone, including the people who sent the message. Does anyone know how I can fix this problems?
Use this code instead.
if ($mail['to_id'] != $account['id'] && $mail['from_id'] != $account['id']) {
$system->message(L_ERROR, L_MAIL_ERROR_PERMISSION, './?area=forum&s=mail', L_CONTINUE);
}
Your logic is:
!$mail['to_id'] == $account['id']
&&
!$mail['from_id'] == $account['id']
The problem stems from doing this:
!$mail['to_id']
and
!$mail['from_id']
The inverse operator (!) flips the value of what it's being applied to. In this case, you're flipping the value of $mail ID's. That's probably not going to do what you're thinking since those ID's, I'm assuming, are integers.
It might help to think of this in the positive and then reverse the whole thing.
The positive is:
$mail['to_id'] == $account['id']
&&
$mail['from_id'] == $account['id']
The inverse of it is wrapping the whole thing in a "!" (note the parenthesis):
!(
$mail['to_id'] == $account['id']
&&
$mail['from_id'] == $account['id']
)
We can use the rules of Algebra to convert that statement by multiplying "!" against each element (including the AND operator).
!($mail['to_id'] == $account['id']) // Note you apply the inverse of to the whole expression
!&& // this isn't an actual code but for demonstration purposes
!($mail['from_id'] == $account['id']) // Note you apply the inverse of to the whole expression
Which simplifies into:
$mail['to_id'] != $account['id'] // Not Equal is inverse of equal
|| // the inverse of && (AND) is || (OR)
$mail['from_id'] != $account['id'] // Not Equal is inverse of equal
Which states:
"If the Mail_To OR Mail_From ID doesn't match the Account ID, execute the following code"
So, at the end of the day you should be able to use:
if( $mail['to_id'] != $account['id'] || $mail['from_id'] != $account['id'] )
{
// do something
}
or
if( !( $mail['to_id'] == $account['id'] && $mail['from_id'] == $account['id']) )
{
// do something
}
Both say the same thing.
I hope that helps!

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