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.
Related
I am having trouble understanding the behavior of the 'and' PHP operator.
Here is the code:
$condition1 = true;
$var2 = "var2";
$var3 = "var3";
$condition2 = $condition1 and $var2 == $var3;
if($condition2)
echo '$condition1 and $var2 == $var3';
Output: $condition1 and $var2 == $var3
Now it is obvious that since $var2 != $var3, $condition2 should be false. Hence the echo statement should not be executed but it happens the other way. Can any one tell me what's wrong with this code?
Use && instead of and.
and has lesser precedence than &&. The statement
$condition2 = $condition1 and $var2 == $var3;
is executed in two steps from left to right.
1: $condition2 = $condition1 is executed. i.e. $condition2 is true now.
2: $var2 == $var3; is executed which performs the evaluation but does not assign any value to any variable.
I think this is an operator precedence issue. Try this instead:
$condition2 = ($condition1 and $var2 == $var3);
I think the issue is that your current code gets interpreted like this:
($condition2 = $condition1) and ($var2 == $var3)
Try this
$condition2 = ($condition1 and $var2 == $var3);
Or this one
$condition2 = ($condition1 && $var2 == $var3);
I want to return a value based on the content of two variables.
Let me explain better, I have three variables:
$var1 = 2; // This variable can change from 1 to 10 (based on the value in the database)
$var2 = 1; // This variable can have two values: 0 and 1 (based on the value in the database)
$result = ''; // This variable have a value based on the content of the two variables
I take two values from two different column of the Database ($var1 and $var2) and I have $result, a variable that have a value based on the content of $var1 and $var2
This can be done easily, making 20 conditions, like this:
if ($var1 == 1 && $var == 0) $result = 'good morning';
if ($var1 == 1 && $var == 1) $result = 'hello';
if ($var1 == 2 && $var == 0) $result = 'never';
But my question is: there is a way for write this piece of code more easily, easy to read and more manageable?
PS: $result have completely different values, concatenation not needed in this case.
Thanks.
I think this might be a more manageable version of your code:
switch([$var1,$var2]) {
case [0,0]:
// code
break;
case [0,1]:
// code
break;
// ...
default:
// pairing wasn't defined
}
Without knowing the exact nature of $var1 and $var2, nor the significance of $result, I can't really help more, but this should be a good start.
All other answers are good, I just want to add another possibility:
Store your result's values into an array, and call/search it like this:
$data[1][0] = 'good morning';
$data[1][1] = 'hello';
$data[2][0] = 'never';
//$data[x][y] = 'result of $var1=x and $var2=y';
// if exists a combination
if (isset($data[$var1][$var2])) {
// get the value
$result = $data[$var1][$var2];
}
$result = 'value' . $var1 . '.' . $var2;
Well, many ways!
Following your piece of code you can build the string:
$result = "$var1" . "." . "$var2";
using the "value-to-string" effect.
You can also return an array:
$result = array("var1" => $var1, "var2" => $var2);
and access each part with $res["var1"/"var2"].
Not sure if concat'ing this is what you're looking for. If it's not, then switch() might be the way to go:
<?php
switch(true){
case ($var1 == 1 && $var == 0):
$result = 'value1.0';
break;
case ($var1 == 1 && $var == 1):
$result = 'value1.1';
break;
case ($var1 == 2 && $var == 0):
$result = 'value2.0'
break;
default:
$result = 'value0.0';
}
?>
Another options, after your edit, would be to make a Matrix:
$m = array();
$m[1] = array(0 => 'good morning', 1 => 'hello');
$m[2] = array(0 => 'never');
$result = isset($m[$var1][$var2])?$m[$var1][$var2]:""; // Or false if you prefer
In PHP, I have seen a lot of people using the this:
if($var1 = myfunction()){
//do something
}
That way, if true the variable already holds the value you need.
Why doesn't the same work with two variables and two functions?
if($var1 = myfunction() && $var2 = myfunction2()){
// Do something
}
When i tried using the above, I always got a "1". Even though both functions return a value. As soon as I removed the second part ($var2 = ) - it worked.
Why do I get a 1?
It's because of operator precedence
php interprets
$var1 = myfunction() && $var2 = myfunction2()
expression as
$var1 = ( myfunction() && ( $var2 = myfunction2() ) )
So:
$var2 = myfunction2() comes first
Then myfunction() && $var2 is evaluated
The result of the latter expression (which is always a boolean) is assigned to $var1
The solution - use parentheses
($var1 = myfunction()) && ($var2 = myfunction2())
The better solution: avoid such expressions
So I have 2 variables, var1, var2.
$var1 = "53,000,000" //- integer
$var2 = 10 //- string
In the end I want to compare both, so I
$var1 = (int)str_replace(",","",$var1); // => 53000000 - integer
Here's my issue .. if I do:
if($var1 > $var2)
$var2 = $var1
I get $var2 = 0 .... Why ?
.. running on PHP 5.2.14
EDIT Accidentally typed in substr_replace instead of str_replace. Updated.
I had to add a couple semicolons, but here's the code:
$var1 = "53,000,000"; //- integer
$var2 = 10; //- string
//In the end I want to compare both, so I
$var1 = (int)str_replace(",","",$var1); // => 53000000 - integer
//Here's my issue .. if I do:
if($var1 > $var2)
$var2 = $var1;
var_dump($var1, $var2);
And here's my output:
int(53000000) int(53000000)
I used 5.2.6, but it shouldn't matter. Do you have any other code in between what you're showing?
Use str_replace() instead of substr_replace().
You've specified the wrong parameters for substr_replace, so $var1 is evaluated to 0. I guess you wanted to use str_replace.
No need for type casting. just do the str_replace
Here is code
$var1 = "53,000,000" ;
$var2 = 10;
$var1=str_replace(',','',$var1);
if($var1 > $var2)
$var2 = $var1;
echo $var2;
$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