PHP long if statement not working - php

I have this if statment here and its not working
if(
($division->id == 1 || $division->id == 2) &&
in_array('member1', $memberships) ||
in_array('member2', $memberships) ||
in_array('member3', $memberships) ||
in_array('member4', $memberships) ||
($division->id != 1 || $division->id != 2)
&& in_array('member5', $memberships))
{
return FALSE;
} else {
return TRUE;
}
What I am trying to do is say if $division is 1 or 2 and if member1, member2, member3, member4 are in the array $memberships return false, if $division is not 1 or 2 and member5 is in the array return false, everything else return true.
This is not working because member5 is in the array and $division is 1, which should return true, but it returns false.
PS - member1-5 are just names I am using for here as they actually are personal information in my array.
What Am i doing wrong?

I'd do this as a series of different 'if' statements, to avoid you going around the bend trying to work it out.
I've created this piece of code according to your statement...
What I am trying to do is say if $division is 1 or 2 and if member1,
member2, member3, member4 are in the array $memberships return false,
if $division is not 1 or 2 and member5 is in the array return false,
everything else return true.
I think I've got the logic right, I'm about to double check it:
if ($division->id == 1 || $division->id == 2)
{
if (in_array("member_2", $memberships) || in_array("member_3", $memberships) || in_array('member_3', $memberships) || in_array('member_4', $memberships))
{
return false;
}
else
{
return true;
}
}
else
{
if (in_array("member_5", $memberships))
{
return false;
}
else
{
return true;
}
}

These are the logical groupings, 1 per line. Use parenthesis to adjust how php evaluates it if this isnt what you want.
($division->id == 1 || $division->id == 2) && in_array('member1', $memberships)
|| in_array('member2', $memberships)
|| in_array('member3', $memberships)
|| in_array('member4', $memberships)
|| ($division->id != 1 || $division->id != 2) && in_array('member5', $memberships))

Try:
if(
(($division->id == 1 || $division->id == 2) &&
(in_array('member1', $memberships) ||
in_array('member2', $memberships) ||
in_array('member3', $memberships) ||
in_array('member4', $memberships))) ||
(($division->id != 1 || $division->id != 2)
&& in_array('member5', $memberships)))
{
return FALSE;
} else {
return TRUE;
}

Less lines of code does not always mean it's better, break it down and make it readable, for example:
$output = true;
if($division->id == 1 || $division->id == 2)
{
if(in_array("member_2", $memberships) || in_array("member_3", $memberships) || in_array('member_4', $memberships))
{
$output = false;
}
}
else
{
if (in_array("member_5", $memberships))
{
$output = false;
}
}
return $output;

Related

undefined index but i can't understand why

Here is my code
if (isset($_POST['error']) && $_POST['error'] != 2 && $_POST['error'] != 1) {
return true;
} else if (isset($_POST['error']) && $_POST['error'] == 2 || $_POST['error'] == 1) {
return false;
} else {
return false;
}
Please help.
Thanks.
When you do && it will evaluate all conditions until something is false. When you do || it will evaluate all conditions until something is true. Since your first conditions evaluated to the false, the 2nd one was invoked but $_POST['error'] didn't exist.
You probably want to do this, notice the brackets around your two errors.
if(
isset($_POST['error']) &&
(
$_POST['error'] == 2 ||
$_POST['error'] == 1
)
)
It can also be better re-written as.
if(
isset($_POST['error']) &&
in_array($_POST['error'], array(1,2))
)
Like Augwa said:
The && operator will evaluate all conditions until any one of them is false.
The || operator will evaluate all conditions until any one of the is true.
A solution:
if(isset($_POST['error'])) {
if($_POST['error'] != 2 && $_POST['error'] !=1) {
// Do stuff here
return true;
}else if($_POST['error'] == 2 || $_POST['error'] == 1) {
return false;
} else {
return false;
}
}
you should change your code as below... always enclose your comparison with || in brackets. because || condition checks up to last piece of code to find out a 'true' value. by re-coding as ..... && (... || .... ), the executions will return from the point && and will not execute ( .... || ..... ) part
if (isset($_POST['error']) && $_POST['error'] != 2 && $_POST['error'] != 1) {
return true;
} else if (isset($_POST['error']) && ($_POST['error'] == 2 || $_POST['error'] == 1)) {
return false;
} else {
return false;
}

In PHP how do you do an if statement within the if of an if statement?

So the question is confusing I know. This is what I am wondering how to do.
I have the following if statement:
if(
(isset($_POST['billing_company']) && $_POST['billing_company'] != "") &&
(isset($_POST['billing_address']) && $_POST['billing_address'] != "") &&
(isset($_POST['billing_city']) && $_POST['billing_city'] != "") &&
(isset($_POST['billing_state']) && $_POST['billing_state'] != "") &&
(isset($_POST['billing_zip']) && $_POST['billing_zip'] != "") &&
(isset($_POST['billing_phone']) && $_POST['billing_phone'] != "") &&
(isset($_POST['location_name']) && $_POST['location_name'] != "") &&
(isset($_POST['location_address']) && $_POST['location_address'] != "") &&
(isset($_POST['location_city']) && $_POST['location_city'] != "") &&
(isset($_POST['location_state']) && $_POST['location_state'] != "") &&
(isset($_POST['location_zip']) && $_POST['location_zip'] != "") &&
(isset($_POST['location_phone']) && $_POST['location_phone'] != "") &&
(isset($_POST['user_firstname']) && $_POST['user_firstname'] != "") &&
(isset($_POST['user_lastname']) && $_POST['user_lastname'] != "") &&
(isset($_POST['user_username']) && $_POST['user_username'] != "") &&
(isset($_POST['user_email']) && $_POST['user_email'] != "") &&
(isset($_POST['user_password']) && $_POST['user_password'] != "") &&
(isset($_POST['user_mobile']) && $_POST['user_mobile'] != "") &&
(isset($_POST['payment_cc_name']) && $_POST['payment_cc_name'] != "") &&
(isset($_POST['payment_cc_number']) && $_POST['payment_cc_number'] != "") &&
(isset($_POST['payment_cc_expo_month']) && $_POST['payment_cc_expo_month'] != "") &&
(isset($_POST['payment_cc_expo_year']) && $_POST['payment_cc_expo_year'] != "") &&
(isset($_POST['payment_cc_code']) && $_POST['payment_cc_code'] != "") &&
(isset($_POST['terms']) && $_POST['terms'] != "")
){
However, based on some variables, I may no longer need any of the billing information. So I am wondering if I can do an IF inside the IF, so something like this:
if(
($billingRequired == 1){
(isset($_POST['billing_company']) && $_POST['billing_company'] != "") &&
(isset($_POST['billing_address']) && $_POST['billing_address'] != "") &&
(isset($_POST['billing_city']) && $_POST['billing_city'] != "") &&
(isset($_POST['billing_state']) && $_POST['billing_state'] != "") &&
(isset($_POST['billing_zip']) && $_POST['billing_zip'] != "") &&
(isset($_POST['billing_phone']) && $_POST['billing_phone'] != "") &&
}
(isset($_POST['location_name']) && $_POST['location_name'] != "") &&
(isset($_POST['location_address']) && $_POST['location_address'] != "") &&
(isset($_POST['location_city']) && $_POST['location_city'] != "") &&
(isset($_POST['location_state']) && $_POST['location_state'] != "") &&
(isset($_POST['location_zip']) && $_POST['location_zip'] != "") &&
(isset($_POST['location_phone']) && $_POST['location_phone'] != "") &&
(isset($_POST['user_firstname']) && $_POST['user_firstname'] != "") &&
(isset($_POST['user_lastname']) && $_POST['user_lastname'] != "") &&
(isset($_POST['user_username']) && $_POST['user_username'] != "") &&
(isset($_POST['user_email']) && $_POST['user_email'] != "") &&
(isset($_POST['user_password']) && $_POST['user_password'] != "") &&
(isset($_POST['user_mobile']) && $_POST['user_mobile'] != "") &&
(isset($_POST['payment_cc_name']) && $_POST['payment_cc_name'] != "") &&
(isset($_POST['payment_cc_number']) && $_POST['payment_cc_number'] != "") &&
(isset($_POST['payment_cc_expo_month']) && $_POST['payment_cc_expo_month'] != "") &&
(isset($_POST['payment_cc_expo_year']) && $_POST['payment_cc_expo_year'] != "") &&
(isset($_POST['payment_cc_code']) && $_POST['payment_cc_code'] != "") &&
(isset($_POST['terms']) && $_POST['terms'] != "")
){
I'm pretty sure there isn't but wanted to check with people smarter than me. I know I can do some nesting in side the {} but wanted to not have to check each variable inside a very deep nest.
Thanks,
Just add () around the section you want to combine and it will resolve to a simple boolean which can be included in your if statement
The logic here reads "if (billing is not required or billing fields are all filled out) and all the non-billing fields are filled out, then..."
if(
(($billingRequired != 1) || (
(isset($_POST['billing_company']) && $_POST['billing_company'] != "") &&
(isset($_POST['billing_address']) && $_POST['billing_address'] != "") &&
(isset($_POST['billing_city']) && $_POST['billing_city'] != "") &&
(isset($_POST['billing_state']) && $_POST['billing_state'] != "") &&
(isset($_POST['billing_zip']) && $_POST['billing_zip'] != "") &&
(isset($_POST['billing_phone']) && $_POST['billing_phone'] != "")
))
&&
(
(isset($_POST['location_name']) && $_POST['location_name'] != "") &&
(isset($_POST['location_address']) && $_POST['location_address'] != "") &&
(isset($_POST['location_city']) && $_POST['location_city'] != "") &&
(isset($_POST['location_state']) && $_POST['location_state'] != "") &&
(isset($_POST['location_zip']) && $_POST['location_zip'] != "") &&
(isset($_POST['location_phone']) && $_POST['location_phone'] != "") &&
(isset($_POST['user_firstname']) && $_POST['user_firstname'] != "") &&
(isset($_POST['user_lastname']) && $_POST['user_lastname'] != "") &&
(isset($_POST['user_username']) && $_POST['user_username'] != "") &&
(isset($_POST['user_email']) && $_POST['user_email'] != "") &&
(isset($_POST['user_password']) && $_POST['user_password'] != "") &&
(isset($_POST['user_mobile']) && $_POST['user_mobile'] != "") &&
(isset($_POST['payment_cc_name']) && $_POST['payment_cc_name'] != "") &&
(isset($_POST['payment_cc_number']) && $_POST['payment_cc_number'] != "") &&
(isset($_POST['payment_cc_expo_month']) && $_POST['payment_cc_expo_month'] != "") &&
(isset($_POST['payment_cc_expo_year']) && $_POST['payment_cc_expo_year'] != "") &&
(isset($_POST['payment_cc_code']) && $_POST['payment_cc_code'] != "") &&
(isset($_POST['terms']) && $_POST['terms'] != "")
)
{
//statements
}
Although I suspect this could be done better within a loop, maybe it's personal preference, but I'd be happier with something like this
$billingRequiredFields = array('billing_company','billing_address','billing_city','billing_state','billing_zip','billing_phone','location_name','location_address','location_city','location_state','location_zip','location_phone','user_firstname','user_lastname','user_username','user_email','user_password','user_mobile','payment_cc_name','payment_cc_number','payment_cc_expo_month','payment_cc_expo_year','payment_cc_code','terms');
$billingNotRequiredFields = array('location_name','location_address','location_city','location_state','location_zip','location_phone','user_firstname','user_lastname','user_username','user_email','user_password','user_mobile','payment_cc_name','payment_cc_number','payment_cc_expo_month','payment_cc_expo_year','payment_cc_code','terms')
$requiredFields = ($billingRequired == 1) ? $billingRequiredFields : $billingNotRequiredFields;
$continue = true;
foreach($requiredFields as $field) {
if (!isset($_POST[$field]) || $_POST[$field] == '') {
$continue = false;
break;
}
}
if ($continue) {
// statements
}
What I would do is create an array at the top of the script that contains a list of all the POSTed variables that are required, then I would just loop through them. Your code would be way smaller. and almost as concise....
//We NEED these fields for the script to work...
$requiredFields = array(
"fname",
"lname",
"phone",
"accredited",
"etc, etc"
);
//IF you require billing,
if($billingRequired){
// Define the billing fields that we expect to be POSTed...
$billingFields = array(
"billing_compnay",
"billing_address",
"etc, etc"
);
// Add the billing fields to the required fields
$requiredFields = array_merge($requiredFields, $billingFileds);
}
// Loop through required fields and check to see if they are all POSTed
foreach($requiredFields as $fieldName){
// IF a required field is not set...
if(empty($_POST[$fieldName])){
// Do stuff, call a function, show an error, etc.
break; // Or redirect, or exit after a JSON response, whatever. Just be sure to end the loop here for efficiency.
}
}
better yet, don't put so many tests in the primary conditional, just make a function to test it, and then test for === true or === false
function validate_input($billingRequired=0){
$b_valid = true;
if( $billingRequired == 1 ){
if (!isset($_POST['billing_company']) || $_POST['billing_company'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['billing_address']) || $_POST['billing_address'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['billing_city']) || $_POST['billing_city'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['billing_state']) || $_POST['billing_state'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['billing_zip']) || $_POST['billing_zip'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['billing_phone']) || $_POST['billing_phone'] == ""){
$b_valid = false;
}
}
if (!isset($_POST['location_name']) || $_POST['location_name'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['location_address']) || $_POST['location_address'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['location_city']) || $_POST['location_city'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['location_state']) || $_POST['location_state'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['location_zip']) || $_POST['location_zip'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['location_phone']) || $_POST['location_phone'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['user_firstname']) || $_POST['user_firstname'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['user_lastname']) || $_POST['user_lastname'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['user_username']) || $_POST['user_username'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['user_email']) || $_POST['user_email'] != "") == ""){
$b_valid = false;
}
elseif (!isset($_POST['user_password']) || $_POST['user_password'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['user_mobile']) || $_POST['user_mobile'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['payment_cc_name']) || $_POST['payment_cc_name'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['payment_cc_number']) || $_POST['payment_cc_number'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['payment_cc_expo_month']) || $_POST['payment_cc_expo_month'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['payment_cc_expo_year']) || $_POST['payment_cc_expo_year'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['payment_cc_code']) || $_POST['payment_cc_code'] == ""){
$b_valid = false;
}
elseif (!isset($_POST['terms']) || $_POST['terms'] == "")
$b_valid = false;
}
return $b_valid;
}
now it's easy to modify / read etc. Because empty can be slightly ambiguous I find myself avoiding it as a rule, despite it's stylistic elegance.
To make this even cleaner, I'd probably write it like this:
function validate_input($billingRequired=0){
$b_valid = true;
$a_billing = array('billing_company','billing_address'...);
$a_main = array('billing_address','location_address'...);
if( $billingRequired == 1 ){
$a_main = array_merge($a_billing,$a_main);
}
foreach ($a_main as $test){
if (!isset($_POST[$test]) || trim($_POST[$test]) == "")
$b_valid = false;
break;
}
}
return $b_valid;
}
With the caveat that assumes empty values are "", which wouldn't generally be the case for select lists etc.

Function always returning true no matter input

I trying to create a function that matches the first number in a string to a state. For example if the user inputs a number that starts with 3, and the state 'vic', then the form should not present any errors. However no matter what is entered the function always returns true. Any help would be appreciated.
$state = array('Please Select', 'VIC', 'NSW', 'QLD', 'NT', 'WA', 'SA', 'TAS', 'ACT'); //In the form this is a drop down menu
$selected_key = $_POST['state'];
$postcode = $_POST["postcode"]; //The full number entered by the user
$errMsg .= validatePS($postcode, $selected_key);
function validatePS($ps, $state) {
$errMsg ="";
$digit = $ps[0]; //Takes the first number from full postcode
$valid = false;
if (($digit == 3) or ($digit == 8) && ($state == 'vic'))
{
$post = true;
}
if (($digit == 1) or ($digit == 2) && ($state == 'nsw'))
{
$post = true;
}
if (($digit == 4) or ($digit == 9) && ($state == 'qld'))
{
$post = true;
}
if ($valid == false) {
$errMsg .= "<p>Match the correct postcode to state</p>";
}
return $errMsg;
}
if ($errMsg !=""){
echo "<p>Please correct the following errors...</p>"; //Prints out errors
echo "<p>$errMsg</p>";
}
You have two "flag" variables - $post which you are updating and $valid which you rely on. If you reduce them to one variable, you should get the behavior you want:
function validatePS($ps, $state) {
$errMsg ="";
$digit = $ps[0]; //Takes the first number from full postcode
$valid = false;
if (($digit == 3) or ($digit == 8) && ($state == 'vic'))
{
$valid = true;
}
if (($digit == 1) or ($digit == 2) && ($state == 'nsw'))
{
$valid = true;
}
if (($digit == 4) or ($digit == 9) && ($state == 'qld'))
{
$valid = true;
}
if ($valid == false) {
$errMsg .= "<p>Match the correct postcode to state</p>";
}
return $errMsg;
}
Note that you could clean up this code considerably by using logical operators instead of multiple if statements:
function validatePS($ps, $state) {
$errMsg ="";
$digit = $ps[0]; //Takes the first number from full postcode
$valid = false;
if ((($digit == 3) or ($digit == 8) && ($state == 'vic')) ||
(($digit == 1) or ($digit == 2) && ($state == 'nsw')) ||
(($digit == 4) or ($digit == 9) && ($state == 'qld'))) {
$errMsg .= "<p>Match the correct postcode to state</p>";
}
return $errMsg;
}

why am i getting a syntax error for the if statement below

if($gradeArray[1] == NULL ||is_nan($gradeArray[1]) || $gradeArray[2] == NULL || is_nan($gradeArray[2]) || $gradeArray[3] == NULL || is_nan($gradeArray[3]) || $gradeArray[4] == NULL || is_nan($gradeArray[4]) || $gradeArray[5] == NULL || is_nan($gradeArray[5]) || $gradeArray[6] == NULL || is_nan($gradeArray[6]) || $gradeArray[7] == NULL || is_nan($gradeArray[7]) || $gradeArray[8] == NULL || is_nan($gradeArray[8]) || $gradeArray[9] == NULL || is_nan($gradeArray[9]) || $gradeArray[0] == NULL || is_nan($gradeArray[0])){
echo "<h2>Please enter scores in ALL textboxes.</h2>";
} else {
//pass array into the function
arrayFunction($gradeArray);
}
$hasErrors = false;
foreach ($gradeArray as $gradeValue) {
if (!is_numeric($gradeValue)) {
$hasErrors = true;
}
}
if ($hasErrors) {
echo "<h2>Please enter scores in ALL textboxes.</h2>";
} else {
arrayFunction($gradeArray);
}
Explanation: Instead of checking each value in the array individually if it is null or not a number, you can iterate over each element in the array and check if it is not numeric (is_numeric()), which includes the check for null.

Need help converting a snippet of code from PHP to Javascript

below is a snippet of code that I started with... then I made some changes based on the commented suggestion from stackoverflow user. (Please see below for my progress so far)
ORIGINAL
$valid = true;
// basic validation
$phoneNumber = str_replace( ' ', '', $phoneNumber );
if ( strlen( $phoneNumber ) < 10 || !is_numeric( $phoneNumber ) ) {
$valid = false;
}
$areaCode = substr($phoneNumber, 0, 3);
$prefix = substr($phoneNumber, 3, 3);
$mainPhone = substr($phoneNumber, 3, 7);
// perform the same regex matching:
if ($valid) {
$regex = '/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/';
$valid = preg_match($regex, $areaCode);
}
if ($valid) {
$regex = '/^(?!\d[1]{2}|[5]{3})([2-9]\d{2})([. -]*)\d{4}$/';
$valid = preg_match($regex, $mainPhone);
}
// perform the original web validation:
if ( $valid ) {
// validate area code
if (
$areaCode == '000' ||
$areaCode == '111' ||
$areaCode == '222' ||
$areaCode == '333' ||
$areaCode == '444' ||
$areaCode == '555' ||
$areaCode == '666' ||
$areaCode == '777' ||
$areaCode == '999' ||
$areaCode == '123' || (is_string($areaCode) && !is_numeric($areaCode))) {
$valid = false;
}
}
if ( $valid ) {
// validate prefix
if ( $prefix == '123' ||
$prefix == '000' ||
$prefix == '111' ||
$prefix == '555' || (is_string($prefix) && !is_numeric($prefix))) {
$valid = false;
}
}
if ( $valid ) {
// validate main phone number
if ( $mainPhone == '2222222' ||
$mainPhone == '3333333' ||
$mainPhone == '4444444' ||
$mainPhone == '6666666' ||
$mainPhone == '7777777' ||
$mainPhone == '8888888' ||
$mainPhone == '9999999' || (is_string($phoneNumber) && !is_numeric($phoneNumber))) {
$valid = false;
}
}
return $valid;
NEW JAVASCRIPT VERSION (SO FAR)
below is a snippet of code that I am converting so far... I still have some PHP stuff in there can you guys help me out to remove/replace what this snippet needs to say to make it work?
function is_numeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function phonenumberIsValid(phonenumber)
{
var valid = true;
// basic validation
var phonetest = phonenumber.replace(' ','');
if ( strlen( phonetest ) < 10 || !is_numeric( phonetest ) ) {
valid = false;
}
var areaCode = phonetest.substr(0,3);
var prefix = phonetest.substr(3,3);
var mainPhone = phonetest.substr(3,7);
// perform the same regex matching that LeadMaster does:
if(valid){
valid = areaCode.match('/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/');
}
if(valid){
valid = mainPhone.match('/^(?!\d[1]{2}|[5]{3})([2-9]\d{2})([. -]*)\d{4}$/');
}
// perform the original web validation:
if(valid){
// validate area code
if (
areaCode == '000' ||
areaCode == '111' ||
areaCode == '222' ||
areaCode == '333' ||
areaCode == '444' ||
areaCode == '555' ||
areaCode == '666' ||
areaCode == '777' ||
areaCode == '999' ||
areaCode == '123' || (!is_numeric(areaCode)) {
valid = false;
}
}
if(valid) {
// validate prefix
if ( prefix == '123' ||
prefix == '000' ||
prefix == '111' ||
prefix == '555' || (!is_numeric(prefix)) {
valid = false;
}
}
if(valid) {
// validate main phone number
if ( mainPhone == '2222222' ||
mainPhone == '3333333' ||
mainPhone == '4444444' ||
mainPhone == '6666666' ||
mainPhone == '7777777' ||
mainPhone == '8888888' ||
mainPhone == '9999999' || (!is_numeric(phoneNumber)) {
valid = false;
}
}
return valid;
}
PregMatch can be replaced with "myString".match so for instance.
if ($valid) {
$regex = '/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/';
$valid = preg_match($regex, $areaCode);
}
would become
if(valid){
valid = areaCode.match('/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/');
}
and
str_replace("search","replace",$myString)
becomes
myString.replace("search","replace")
In fact most of this can be worked out yourself by typing things like "str_replace javascript" into google and looking for the previous stack overflow answer :)

Categories