I would like to get rid off if else condition and return condition result directly.
if(Condition 1 || condition 2 ){
return true;
} else {
return false;
}
something like this?
$a = 2;
$b = (( $a < 5 || $a >= 5 )?TRUE:FALSE);
// Result for $b
TRUE
Related
Is there an elegant way to check if multiple, but not all, conditions are true out of any given number of conditions?
For example, I have three variables: $a, $b, and $c.
I want to check that any two of these are true. So the following would pass:
$a = true;
$b = false;
$c = true;
But this wouldn't:
$a = false;
$b = false;
$c = true;
Also, I may want to check if 4 out of 7 conditions were true, for example.
I realise I can check each combination, but this would get more difficult as the number of conditions increased. Looping through the conditions and keeping a tally is the best option I can think of, but I thought there may be a different way to do this.
Thanks!
Edit: Thanks for all the great answers, they're much appreciated.
Just to throw a spanner in to the works, what if the variables weren't explicit booleans?
E.g.
($a == 2)
($b != "cheese")
($c !== false)
($d instanceof SomeClass)
A "true" boolean in PHP casts to a 1 as an integer, and "false" casts to 0. Hence:
echo $a + $b +$c;
...will output 2 if two out of the three boolean variables $a, $b or $c are true. (Adding the values will implicitly convert them to integers.)
This will also work with functions like array_sum(), so for example:
echo array_sum([true == false, 'cheese' == 'cheese', 5 == 5, 'moon' == 'green cheese']);
...will output 2.
You could put your variables in an array, and use array_filter() and count() to check the number of true values:
$a = true;
$b = false;
$c = true;
if (count(array_filter(array($a, $b, $c))) == 2) {
echo "Success";
};
I'd go for a method like the following:
if (evaluate(a, b, c))
{
do stuff;
}
boolean evaluate(boolean a, boolean b, boolean c)
{
return a ? (b || c) : (b && c);
}
What it says is:
If a is True, then one of b or c must be true too to comply with 2/3
True criterion.
Else, both b and c must be true!
If you want to expand and customise the conditions and the number of variables I'd go for for a solution like the following:
$a = true;
$b = true;
$c = true;
$d = false;
$e = false;
$f = true;
$condition = 4/7;
$bools = array($a, $b, $c, $d, $e, $f);
$eval = count(array_filter($bools)) / sizeof($bools);
print_r($eval / $condition >= 1 ? true : false);
Simply we evaluate the true's and we make sure that the % of True is equals or is better than what we want to achieve. Likewise you could manipulate the final evaluation expression to achieve what you want.
This should also work, and would allow you fairly easily to adjust to the numbers.
$a = array('soap','soap');
$b = array('cake','sponge');
$c = array(true,true);
$d = array(5,5);
$e = false;
$f = array(true,true);
$g = array(false,true);
$pass = 4;
$ar = array($a,$b,$c,$d,$e,$f,$g);
var_dump(trueornot($ar,$pass));
function trueornot($number,$pass = 2){
$store = array();
foreach($number as $test){
if(is_array($test)){
if($test[0] === $test[1]){
$store[] = 1;
}
}else{
if(!empty($test)){
$store[] = 1;
}
}
if(count($store) >= $pass){
return TRUE;
}
}
return false;
}
U can use while loop :
$condition_n = "x number"; // number of required true conditions
$conditions = "x number"; // number of conditions
$loop = "1";
$condition = "0";
while($loop <= $conditions)
{
// check if condition is true
// if condition is true : $condition = $condition + 1;
// $loop = $loop + 1;
}
if($condition >= $condition_n)
{
// conditions is True
}
else
{
// conditions is false
}
I think it is a little easy and short writing when you use operator "&" , "|" like this:
$a = true;
$b = true;
$c = false;
$isTrue = $a&$b | $b&$c | $c&$a;
print_r( $isTrue );
Let check by your self :D
i have a problem with my function which should combine logical operators according to data in array:
$arr = array(
0 => array(false, "or"),
1 => array(false, "or"),
2 => array(true)
);
the equation should be:
false or false or true
($arr[0][0] $arr[0][1] $arr[1][0] $arr[1][1] $arr[2][0])
And the result: true
But something wrong happens in function and it returns false.
What am i missing?
var_dump( arrayBoolValidation($arr) );
function arrayBoolValidation (array $arr) {
$num = count($arr);
$status = $arr[0][0];
for($i = 1; $i < $num; ++$i) {
if ($arr[$i-1][1] == "and") {
$status = filter_var($status, FILTER_VALIDATE_BOOLEAN) and filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN);
} else if ($arr[$i-1][1] == "or") {
$status = filter_var($status, FILTER_VALIDATE_BOOLEAN) or filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN);
}
}
return $status;
}
It's an operator precedence issue. and is not the same as &&. Look at http://php.net/manual/en/language.operators.precedence.php
= has higher priority than and, so $a = $b and $c; equals to $a = $b;.
You must use extra brackets ($a = ($b and $c);) or better use &&. Same thing about or (use ||).
Assuming that all conditions have to be evaluated:
Note: I have added the case when no operator is defined.
[...]
if (!isset($arr[$i-1][1])) {
$status = $status || $arr[$i][0]; // default: OR, && else
} else if ($arr[$i-1][1] == "and") {
$status = $status && $arr[$i][0];
} else if ($arr[$i-1][1] == "or") {
$status = $status || $arr[$i][0];
}
[...]
Change the following inside your loop:
if ($arr[$i-1][1] == "and") {
$status = (filter_var($status, FILTER_VALIDATE_BOOLEAN) and filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN));
} else if ($arr[$i-1][1] == "or") {
$status = (filter_var($status, FILTER_VALIDATE_BOOLEAN) or filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN));
}
You'll see the extra brackets.
If you don't put them, you set $status to filter_var($status, FILTER_VALIDATE_BOOLEAN), which will always be the same as the first entry (false in this case).
I think there is something wrong in loop
try,
for($i = 1; $i <=$num; ++$i) {
Any ideas how to shorten if statment in an elegant way.
My if statement:
if(getfoo1() == getfoo2() && getfoo2() == 1)
{
}
EDIT:
I'm looking for something like:
if(getfoo1() == getfoo2() ==1)
{
}
But I suppose we can't do this.
$a = getfoo1();
$b = getfoo2(); // less operations, while it not produces duplicate calls
if($a == $b && $b == 1){
// do something
}
$variable = ((getfoo1() == getfoo2() && getfoo2() == 1) ? $value1 : $value2);
More elegant, combined:
$a = getfoo1();
$b = getfoo2();
$variable = (($a == $b && $b == 1) ? $value1 : $value2);
Since we don't know the possible return values from the functions, if you assume they are integers then you can say:
$a = getfoo1();
$b = getfoo2();
if (($a * $b) === 1) { // strict equality for the win
echo 'hi';
}
The result would only be true iff both $a AND $b are 1.
Another way:
$both = array(getfoo1(), getfoo2());
// use array_diff_assoc so it checks multiple occurrences of the same value
$diffCount = count(array_diff_assoc($both, array(1, 1)));
if ($diffCount === 0) {
echo 'hi';
}
Since anyway getfoo2() == 1 must be true, a better approach is to first check whether getfoo2() is equal to 1. If it false no matter about 2nd condition. But If you first check getfoo1() == getfoo2() and and then check getfoo2() == 1 you have to check 2 conditions all the times.
Therefore go for
$a = getfoo1();
$b = getfoo2();
if($b == 1 && $a == $b)
{
// logiv
}
else
{
}
Try this.
$a = getfoo1();
$b = getfoo2();
if( intval($a && $b) === 1) {
echo 'hi';
}
I have this code:
If(!isset($a) || empty($a))
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
The issue is that when $a is equal 0 then empty($a) is true and the first code runs. I need the second one to run. How do I do it?
if (isset($a) && $a == 0)
{
//code to run when $a is equal 0
}
elseif (empty($a))
{
// code to run when $a not set or empty;
}
else
{
//code to run in all other scenarios
}
Try this:
if((!isset($a) || empty($a)) && $a !== 0)
{
// code runs when $a not set or empty and $a is not 0;
}
elseif ($a === 0)
{
//code runs when $a is equal 0
}
else
{
//code runs in all other scenarios
}
Update:
Changed to typesafe comparison.
replace this and try
If(!isset($a) || $a=='')
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
I found the solution:
if (!isset($a) || (empty($a) && $a!==0))
{
//run code if $a is not set or is empty
}
elseif ($a===0)
{
//run code if $a is 0;
}
else
{
//all other scenarios
}
Empty function returns false when 0 (0 as an integer).
So your code should be
If(!isset($a))
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
I'm wanting to set the condition of a do-while loop with a variable. Here's my code...
$ans_type = mt_rand(1, 2);
if ($ans_type == 1){
$condition = '$work_b != $c';
$symbol = '=';
$final_note = '1';
} else {
$condition = '$work_b == $c';
$symbol = '≠';
$final_note = '2';
}
do{
$a = mt_rand(-25, 25);
$b = mt_rand(-25, 25);
$c = mt_rand(-25, 25);
$d = mt_rand(-25, 25);
if($op_1 == '–'){
$work_b = $b * -1;
} else {
$work_b = $b;
}
if($op_2 == '–'){
$work_d = $d * -1;
} else {
$work_d = $d;
}
} while ($a == 0 || $b == 0 || $c == 0 || $d == 0 || $condition);
Note the $condition variable that I want to put in the while() part of the loop. This produces an infinite loop though.
So, is there a way to use variables as conditions in loops?
You can use variables as conditions, however the reason your code produces an infinite loop is because you are not changing $condition within your while loop. Therefore, if $condition evaluates to true once, it will keep evaluating to true (as it never changes in your code).
What you're trying to do can be better achieved by using normal variables:
if( blah ) {
$conditionstate = false;
} else {
$conditionstate = true;
}
...
} while( ... || ($work_b == $c) == $conditionstate );
If you have more varied conditions, maybe a restructure is in order. If there really is no way to restructure it, I'm hesitant to suggest it, because so many people misuse it to terrible consequences, but eval does what you're looking for and can be safe (if not fast) if used carefully. Needing to use it is usually a sign that your program has a bad structure though.
p.s. These types of random number generation problems are much better solved with code like this:
$a = mt_rand(-25, 24);
if( $a >= 0 ) {
++ $a;
}
// $a is -25 to 25, but never 0
$b = mt_rand(-25, 23);
if( $b >= min( $a, 0 ) ) {
++ $b;
}
if( $b >= max( $a, 0 ) ) {
++ $b;
}
// $b is -25 to 25, but never 0 or a
That can be made more elegant, but you get the idea. No need to loop at all, and guaranteed to halt.
$ans_type = mt_rand(1, 2);
if ($ans_type == 1){
$condition = ($work_b != $c);
$symbol = '=';
$final_note = '1';
} else {
$condition = ($work_b == $c);
$symbol = '≠';
$final_note = '2';
}
You are passing $condition as a string. Just save the $condition variable as a boolean.