sum of ONLY POSITIVE variable in php - php

I have variables $var1, $var2, $var3. Each day they are being fetched from a MYSQL query and being displayed in a row in a table. Sometimes they are positive and sometimes there are negative values. I would like one column to show the sum of only the POSITIVE values. How do I write a php statement to add only the positive values?
Do I need to write 6 if statements or is there an easier way?

You can use PHP Ternary Operator to do it with 4 lines of code.
Simply, if variable is greater than zero, positive (add to sum), else negative (skip, no need to add).
Use ternary operator.
<?php
$sum = 0; // Initialise $sum
$sum += ($var1 > 0) ? $var1 : 0; // If $var1 is greater than 0, add to $sum.
$sum += ($var2 > 0) ? $var2 : 0; // Same as of $var1
$sum += ($var3 > 0) ? $var3 : 0; // Same as of $var1
?>

Related

PHP check if value of array[$i] =!array[$j]

i want to compare two values in one php array but the code stops when i compare even when the conditions is true i want to know how can i compare the two values here is my code :
$i=0;$cmpt=0;
foreach($newarray as $newarray1){
$j=0;
while ($newarray1[$i]!==$newarray1[$j]){ // the iteration dont get in here even when the condition is true
$j+1;
var_dump($j);
}
if ($i=$j){
$couleur[]=$Tcouleur[$cmpt];
$cmpt+1;
}else{
$couleur[]=$Tcouleur[$j];
}
$i+1;
}
var_dump($couleur);
This is probably because of the line
$j+1;
your both variables ($i and $j) are not being updated in the while loop, causing an infinite loop. ( checking the same values all the time, if the condition is true an infinite loop, else the code will never enter the loop and exit. )
change $j+1; with either $j++; or $j = $j + 1;
Moreover as #apomene shows,
if your array can have multiple types,
The !== operator checks both the type and the equality. If your array has same types ( for e.g int ) this would not create a problem tho. With the same types !== and != are the same thing practically. Else, it (!==) also checks for type equality. To elaborate,
$a = 1;
$b = '1';
$c = 2;
$d = 1;
$a == $b // TRUE ( different type, equal after conversion - char <-> int)
$a === $b // FALSE( different types - int vs char)
$a == $c // FALSE( same type not equal)
$a === $d // TRUE ( same type and equal)
Further reading available in this question.
Lastly, you seem to have a confusion between assignment and comparison of a variable. ( $i = $j vs $i == $j )
Check the php manual for assignment vs comparison of variables.
In your while loop, does $j+1 should not be $j++ or $j = $j + 1 ?
I know it's not the problem your asking...but same for your $i+1 at the end and your $cmpt
Now I think you want this :
$values = ['abc','def', 'hij','klm', 'def', 'klm','nop'];
$couleurs = ['rouge','vert','bleu','jaune','rose'];
$couleurPourValeur = [];
$increment = 0;
foreach($values as $value){
if(!isset($couleurPourValeur[$value])){
$couleurPourValeur[$value] = $couleurs[$increment];
$increment++;
}
}
print_r($couleurPourValeur);

What is the output of parenthesis in php?

$number = 1;
This is valid:
$number = ($number) + 1;
But this is invalid:
$number = ($number) ++;
So why I can use + 1 and increase it but I cannot use ++ to increase it?
$number = ($number) + 1;
This is valid because you add 1 to an expression.
++ as increment operator cannot be used for expressions it can be used only for variables.
From manual:
The increment/decrement operators only affect numbers and strings.
Increment operator ++ increments numbers or string variables. ($number) is not a variable but an expression.
For the same reason that these are valid:
isset($_GET['foo'])
$bar++;
$data = array(1, 5, 6);
sort($data);
... and these are not:
isset('hi');
'hi'++;
33++;
sort(array(1, 5, 6));
Some functions, operators and constructs operate on variables and don't make sense elsewhere. Parenthesis here are basically a red herring.

PHP operator precedence "Undefined order of evaluation"?

http://www.php.net/manual/en/language.operators.precedence.php#example-115
<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3
?>
The example from the php manual doesn't explain very well. Why isn't $a++ evaluated to 2, and then added to 1, so that it always becomes echo 1 + 2 // equals 3? I don't understand how it "may print either 2 or 3". I thought incremental ++ has "higher precedence" than addition +?
In other words, I don't understand why isn't it...
$a = 1;
1) echo $a + $a++;
2) echo 1 + ($a = 1 + 1);
3) echo 1 + (2);
4) echo 3;
It can be either 2 or 3. However in most of the time it will be 3. So why it MIGHT be 2? Because PHP is not describing in which order expressions are evaluated, since it might depends on the PHP version.
Operator precedence in PHP is a mess, and it's liable to change between versions. For that reason, it's always best to use parentheses to group your in-line equations so that there is no ambiguity in their execution.
The example I usually give when asked this question is to ask in turn what the answer to this equation would be:
$a = 2;
$b = 4;
$c = 6;
$val = $a++ + ++$b - 0 - $c - -++$a;
echo $val;
:)
Depending where I run it now, I get anything between 4 and 7, or a parser error.
This will load $a (1) into memory, then load it into memory again and increment it (1 + 1), then it will add the two together, giving you 3:
$a = 1;
$val = $a + ($a++);
This, however, is a parser error:
$a = 1;
$val = ($a + $a)++;
Anyway, long story short, your example 2) is the way that most versions will interpret it unless you add parenthesis around ($a++) as in the example above, which will make it run the same way in all PHP versions that support the incrementation operator. :)
Order of evaluation isn't a precedence issue. It has nothing to do with operators. The problem also happens with function calls.
By the way, $a++ returns the old value of $a. In your example, $a++ evaluates to 1, not 2.
In the following example, PHP does not define which subexpression is evaluated first: $a or $a++.
$a = 1;
f($a, $a++); //either f(1,1) or f(2,1)
Precedence is about where you put in parentheses. Order of evaluation can't be changed by parentheses. To fix order of evaluation problems, you need to break the code up into multiple lines.
$a = 1;
$a0 = $a;
$a1 = $a++;
f($a0, $a1); //only f(1,1)
Order of evaluation only matters when your subexpressions can have side-effects on each other: the value of one subexpression can change if another subexpression is evaluated first.

How to neatly check if 4 variables are the same?

How would someone neatly check if 4 variables are the same?
Obviously this wouldn't work:
if ($var1 === $var2 === $var3 === $var4)
But what would, without writing loads of code?
One way to go would be this:
if ($var1 === $var2 && $var2 === $var3 && $var3 === $var4)
Not a huge amount of code and it gets the job done.
if(!array_diff([$var2, $var3, $var4], [$var1])){
// All equal
}
if ($var1 === $var2 && $var3 === $var4 && $var1 === $var3)
You don't need to check if 2 and 4 are equal
Using array_unique you can check if the array of unique values from the variable list is 1 (which means they are all equal):
if (count(array_unique([$var1, $var2, $var3, $var4])) == 1)
// all equal
This comes in handy especially when comparing a long list of variables, compared to a long list of == checks in an if statement.
You can use ! as your master and use &&
if($var1===$var2 && $var1 === $var3 && $var1 === $var4)
But this wont let you know which of the 4 is not like the others.
In case you are dealing with many variables, I played with the below code and it works.
$m = 'var'; //Assuming you know the variable name format $var1, $var2, $var3,...
for( $n = 1; $n <= 3; $n++) { //testing for 4 variables
$v = "$m$n";
$n++;
$w = "$m$n";
if ( $$v !== $$w ) {
echo "false";
break;
}
$n--;
}
//Breaks and echo "false" as soon as one of the variables is not equal
//Note: increase the iteration for more variable.

Finding a smaller value and swap values in php

$var1 = 22;
$var2 = 10;
echo $var1 = ($var1 < $var2) ? $var1 : $var2; //smaller var
echo '';
echo $var2 = ($var1 > $var2) ? $var1 : $var2; //greater var
I expect it to print 10 and 22 but it prints 10 and 10. any ideas what I am doing wrong?
Thanks
UPDATE
Thanks all.
$min = min($var1, $var2);
$max = max($var1, $var2);
$var1 = $min;
$var2 = $max;
#unicornaddict already solved your problem, but to make it simpler you can use the min and max functions PHP provides.
echo min($var1, $var2), '<br/>', max($var1, $var2);
You are re-assigning the variables in the echo.
// $var1 is being assigned minimum of 10,22 which is 10.
// after this $var1 and $var2 will both be 10.
echo $var1 = ($var1 < $var2) ? $var1 : $var2;
What you want it:
echo ($var1 < $var2) ? $var1 : $var2; // prints min.
echo '<br />';
echo ($var1 > $var2) ? $var1 : $var2; // prints max.
EDIT:
If you always want the smaller of the two values in $var1 you can do:
if($var1 > $var2) { // if $var1 is larger...swap.
list($var1,$var2) = array($var2,$var1);
}
You overwrite $var1 in your first comparison. So the second comparison compares 10 > 10.
$var1 = 22;
$var2 = 10;
echo $var1 = (10 < 22) ? 22 : 10; //smaller var -> $var1 now has the value 10
echo '<br />';
echo $var2 = (10 > 10) ? 22 : 10; //greater var -> 10 is not greater than 10, so $var2 gets a value of 10.
you assign 10 to $var1 with the first echo, so at the second they are both 10.
echo $var1 = ($var1 < $var2) ? $var1 : $var2; //smaller var
This assigns 10 to $var1. Now both variables contain 10. So what do you expect of the second line?
You need a temporary variable. Just use min,
echo min($var1, $var2);
Your question also mentions swapping the values, which the other answers don't seem to make any note of. Given your example code it looks like you want $var1 to contain the smaller of the two values and $var2 the bigger.
$var1 = 22;
$var2 = 10;
if ($var1 > $var2) {
list($var1, $var2) = array($var2, $var1);
}
// $var1 will now be smaller than (or equal to!) $var2

Categories