PHP - How to add up points from a specific value only - php

I want to add up points from the "vak" which is "wiskunde" if the box "vak" is filled with something else than the afformentioned "vak" "wiskunde" it doesnt need to be added up.
pastebin code ugwwDda8
<?php
if($_GET);
{
$jp = $_GET["janpunten"];
$pp = $_GET["pietpunten"];
$kp = $_GET["klaaspunten"];
$janvak = "";
$pietvak = "";
$klaasvak = "";
$totaal = "0";
if ( $janvak && $pietvak && $klaasvak = "Wiskunde" ) {
$totaal = $jp + $pp + $kp;
}
}
?>
So for example, the logic here would be if $janvak $pietvak $klaasvak are all wiskunde, they would add up all the points, but if only $janvak and $pietvak were wiskunde, it would only add up the points from those two.

This doesn't do what you probably think it does:
if ( $janvak && $pietvak && $klaasvak = "Wiskunde" )
This may make sense linguistically when spoken aloud in human languages, but computers don't have human intuition. Each part between the && operators is its own distinct boolean operation. So it's equivalent to this:
if ( ($janvak) && ($pietvak) && ($klaasvak = "Wiskunde") )
There's a pretty good chance that all three of these will always be true. (Or perhaps the first two will always be false? Since they're just empty strings. Either way, the code isn't doing what you want it to do.)
Additionally, you're using the assignment operator (=) instead of the comparison operator (==), so that will also always be true and will modify that variable when performing the if check.
It looks like what you wanted was this:
if ( $janvak == "Wiskunde" && $pietvak == "Wiskunde" && $klaasvak == "Wiskunde" )
When chaining together any combination of boolean logic operations, always make sure that each individual operation is a complete and distinct component of the overall logic.

Related

Is there a way to state multiple conditions associated with another condition as a whole?

I am trying to consolidate a few different if statements. What I am trying to accomplish would read something like this:
If (this is true and this is true) OR (this is true and this is true) AND (This is true)
So, one at least one of the first two sets of parentheses would need to be true, and if one of those is true, then also the last set of parentheses would need to be true, in order for the code inside to be executed.
Here is the specific code I am (unsuccessfully) trying to make work:
if(($calc->number % 2 == 1 && $calc->doubleColor == 'b2' | $calc->number % 2 == 0 && $calc->doubleColor = 'r2') && in_array($calc->number, $backToBet)){
}
Is there a way to do this? A possibility? Is there any drawback to getting a lot into a single if statement?
EDIT
$blackMatch = $calc->number % 2 == 1 && $calc->doubleColor == 'b2';
$redMatch = $calc->number % 2 == 0 && $calc->doubleColor = 'r2';
$numberMatch = in_array($calc->number, $backToBet);
if(($blackMatch || $redMatch) && $numberMatch){
}
/ ** Calc->number = 2, $blackMatch = false, $redMatch = false,
$numberMatch array contains 2 **/
Basically what I end with is a 'true' result, even though neither of the conditions within the inner parentheses are satisfied.
to make code easier to read, I'd suggest to use separate variables, like this:
$condition1 = ($calc->number % 2 == 1) && ($calc->doubleColor == 'b2');
$condition2 = ($calc->number % 2 == 0) && ($calc->doubleColor == 'r2');
$condition3 = in_array($calc->number, $backToBet);
if (($condition1 || $condition2) && $condition3) {
}
two things to note:
|| is logical OR, | is bitwise OR
== is comparison, = is assignment

how to write single line if statement with multiple conditions?

I'm currently working on a foreach loop with nested if statements but I'm pretty sure there's a better way of writing these chunks of if statements.
I found this post: PHP if shorthand and echo in one line - possible?
Though this post is for single conditions, I would like to write mine in the same way(single lined).
I'm not that experienced in PHP myself so I'm sort of stuck on doing it the old fashioned way:
if(($colorLevel['name'] === 'ATTR_VPMCV13') && ($colorLevel['level'] >= 80))
{
$prominentSideNumberArray[] = 10;
}
elseif(($colorLevel['name'] == 'ATTR_VPMCV13') && ($colorLevel['level'] >= 60) && ($colorLevel['level'] <= 70)){
$prominentSideNumberArray[] = 8;
}
If someone could properly explain what code to use where and why, that could really help me, and/or others, out. I've looked at the manual but I just can't figure out what to use where.
There is no such thing like an "if shorthand".
?: is an operator, if is a control structure. They are different language concepts that have different purposes and do different things. An expression that contains the ternary conditional operator (?:) can always be rewritten as two expressions and an if/else statement. The vice-versa is usually not possible.
The code you posted can be written to be much easier to read if you extract the common checking of $colorLevel['name'] into a separate if that includes the rest of the tests, extract $colorLevel['level'] into a new variable with shorter name and make the conditions that use $colorLevel['level'] use the same rule:
$level = $colorLevel['level'];
if ($colorLevel['name'] == 'ATTR_VPMCV13') {
// Don't mix '<=' with '>=', always use '<='...
if (60 <= $level && $level <= 70) {
$prominentSideNumberArray[] = 8;
// ... and put the intervals in ascending order
} elseif (80 <= $level) {
$prominentSideNumberArray[] = 10;
}
}
If there are multiple if statements that verify different values of $colorLevel['name'] then the intention is more clear if you use a switch statement:
$level = $colorLevel['level'];
switch ($colorLevel['name'])
{
case 'ATTR_VPMCV13':
if (60 <= $level && $level <= 70) {
$prominentSideNumberArray[] = 8;
} elseif (80 <= $level) {
$prominentSideNumberArray[] = 10;
}
break;
case '...':
// ...
break;
default:
// ...
break;
}
You can achieve this by using a ternary operator. Look at the following code:
$prominentSideNumberArray[] = ((($colorLevel['name'] === 'ATTR_VPMCV13') &&
($colorLevel['level'] >= 80) )? 10 : (($colorLevel['name'] == 'ATTR_VPMCV13') &&
($colorLevel['level'] >= 60) && ($colorLevel['level'] <= 70)?8:"")) ;
EDIT As per comments and you have to compare same value its better to define name
$color_name = "ATTR_VPMCV13";
if($colorLevel['name'] == $color_name )
$prominentSideNumberArray[] = (($colorLevel['level'] >= 80)? 10 : (
($colorLevel['level'] >= 60) && ($colorLevel['level'] <= 70)?8:"")) ;
DEMO with different approach
EDIT
Keep in mind that this solution is less readable than if-else statement.

PHP Operator failing

I am using this code to select and compare dates and information from 2 separate MySQLi tables. The code should produce the "discount_amount"IF the discount code entered is the same as the discount code in the database OR the discount code in the database is set to "open". Yet even with the dates set and the code set to "open" I am only getting the discount_amount if I type "open" in to the "$design_discount_code" manually.
if($discount_code == $design_discount_code or $discount_code == 'open' && $date >= $discount_start_date && $date <= $discount_end_date){
$design_price_total = $discount_amount;
$discount = 'yes';
} else {
$design_price_total = $original_price;
$discount = 'no';
}
I have also attempted to change the PHP operator to || and xor with no better results. Any ideas as to why it is only returning 'yes' when I type "open" and not automatically as it should?
You seem to assume that or has higher precedence than and. This is incorrect. You should use parentheses to indicate that the or check is one of the and conditions. Like this:
if(($discount_code == $design_discount_code or $discount_code == 'open') and $date >= $discount_start_date and $date <= $discount_end_date)
Also note that mixing the English and/or with the symbolic &&/|| is not a great idea.
Check the priority of the and and or, maybe you can use parentheses () to specify which should be evaluated first.
if( ( $discount_code == $design_discount_code || $discount_code == 'open') && ( $date >= $discount_start_date && $date <= $discount_end_date) )

php error checking mysql date

caveat: i am new to php
I'm reading in 2 dates from a form in a mysql format (i.e. YYYY-MM-DD) and trying to error check them both for validity and that one is less than the other
if(!empty($day1) && !empty($day2)){
$sndate=array();
$sndate = explode('-',$day1);
$sndtnum = implode($sndate);
$sndtnum = (int) $sndtnum;
$unsndate=array();
$unsndate = explode('-',$day2);
$unsndtnum = implode($unsndate);
$unsndtnum = (int) $unsndtnum;
if (!checkdate($sndate[1],$sndate[2],sndate[0]) || !checkdate($unsndate[1],$unsndate[2],unsndate[0]) || $unsndtnum<$sndtnum)
{ $error=True; $errtext .="Date field is filled in wrong \n";
}else {$error=False;}
}
This does not seem to work. I'm pretty sure it's because of the checkdate, but i'm not positive that there isn't also an issue with the implode/cast.
Any ideas on how to fix this?
Apart from the sndate[0] and unsndate[0] variables missing their dollar signs, your check will actually not work if an evil user put non-numeric chars in $day1 (e.g. 2015-09abc-01 will be considered as less than 2015-05-01).
The following approach validates the dates by transforming them from a known format into a DateTime object and then back again, making sure that the two formatted dates are equal:
$f = 'Y-m-d';
$ok1 = ($d1 = DateTime::createFromFormat($f, $day1)) && $d1->format($f) == $day1;
$ok2 = ($d2 = DateTime::createFromFormat($f, $day2)) && $d2->format($f) == $day2;
if ($ok1 && $ok2 && $d1 <= $d2) {
// Ok
} else {
// Error
}
Hope this helps :)

greater or = to a post value

Hi all i have a post value which i am checking to see if its been posted it has atleast 4 numbers (digits) this works perfect.
if (isset($_POST['year']) &&
!preg_match('/([0-9]{4})/i', stripslashes(trim($_POST['year']))) ) {
now i want to check that the value is greater or = to a vairable and not sure how to achive what i need
i tried the below with no luck
$yearOff = date("Y")-150;
echo $yearOff;
if (isset($_POST['year']) &&
!preg_match('/([0-9]{4})/i', stripslashes(trim($_POST['year'])))
&& $_POST['year'] > $yearOff ) {
$ageerrors[] = '<span class="error">
You forgot enter your birth YEAR</span>';
}
Rather than an && you need an || OR condition to switch between the three possible invalid states (empty, not 4+ digits, or <= $yearOff:
if (!isset($_POST['year'])
// Lose the stripslashes()...
|| !preg_match('/([0-9]{4})/i',trim($_POST['year']))
|| $_POST['year'] > $yearOff
) {
// Invalid...
}
Note: It isn't clear from your description whether you want the value to be >= $yearOff or you want it to be < $yearOff. In other words, the code above is testing for the invalid state. Use whichever operator is appropriate for the invalid state.
Note 2: To test for at least 4 consecutive digits in the regex, a better pattern is something like:
/\d{4,}/
// If it must be *only* digits and no other characters, anchor with ^$
/^\d{4,}$/
There's no need for the overhead of a () capture group.
$yearOff = date("Y")-150;
echo $yearOff;
$input = #$_POST['year'];
if (!$input || strlen($input) !== 4 || $input < $yearoff) {
### MEEEP, ERROR ###
}
Explanation:
Input is set (not null which would be false), then it must have a string-length of four and finally it's numerical value must be higher or equal $yearOff.
I assigned the value of the input to it's own variable as well, because you only need to take it once out of $_POST.
As all these conditions are negated, I used the or || operator. Naturally the same can be expressed non-negated and with and:
if ($input && strlen($input) === 4 && $input >= $yearoff) {
### THIS IS CALL OKAY ###
}
To better debug this, the next step is to assign the validity to a variable as well:
$inputValid = $input && strlen($input) === 4 && $input >= $yearoff;
if (false === $inputValid) [
### MEEP, ERROR ####
}
Hope this is helpful.

Categories