How to convert string to conditional boolean
example string with boolean condition.
$condition1 = 'false || ( true && false)'; // should return false
$condition2 = 'false || true'; // should return true
$condition3 = 'true && false'; // should return false
$condition4 = 'true && (true || false); // should return true
I tried these codes but not working..
$result = (boolean) $condition1;
$result = filter_var($condition1, FILTER_VALIDATE_BOOLEAN);
$result = settype($condition1, 'boolean');
is there a way to convert it?
You can use php eval() function
eval("\$status=true || false; return \$status;")
In your case
eval('\$condition1 = false || ( true && false);');
eval('\$condition2 = false || true;');
// And so on ...
Related
I'm writing a functional that calls two nullable boolean APIs. If either API returns true, my function should return true. If both return false, my function should return false. Otherwise, my function should return null. In other words:
true, true -> true
true, false -> true
true, null -> true
false, false -> false
false, null -> null
null, null -> null
Is there a simple/elegant way to write this? Obviously an if-else chain like this would work, but I think it's fairly messy, especially since you have to account for that null is a falsy value.
if ($cond1 || $cond2) {
return true;
} else ($cond1 === false && $cond2 === false) {
return false;
} else {
return null;
}
Stick to what you suggested. One point of improvement is that you don't need if - else branching since you're returning. You just need two ifs:
function evaluate(?bool $cond1, ?bool $cond2): ?bool
{
if ($cond1 || $cond2) {
return true;
}
if ($cond1 === false && $cond2 === false) {
return false;
}
return null;
}
What about
return ($cond1 ? $cond1 : $cond2);
what about :
if($cond1 === true || $cond2 === true){
return true;
}else{ //check first and sec cond for falsing
if($cond1 === false && $cond2 === false){
return false;
}else{ //else null it
return null;
}
}
You can remove else if block like so:
if ($cond1 || $cond2) {
return true;
}
return !isset($cond1, $cond2) ? null : false;
You can simplify it down to:
return ($cond1 || $cond2) ? true : (!isset($cond1, $cond2) ? null : false)
But this gets hard to read and make sense of off.
Given your stipulations (and assuming each argument is one of: null, true or false) you could shave a smidgeon:
function foo($a, $b) {
if($a || $b) return true;
if([$a, $b] === [false, false]) return false;
}
Below seems to be working, I have tried to logic using Javascript as illustrated below
function testMyConditions($c1, $c2) {
return ($c1 === true || $2 === true) ? true: ($c1 === null || $c2 === null ? null: false)
}
function testMyConditions($cond1, $cond2) {
return ($cond1 === true || $cond2 === true) ? true: ($cond1 === null || $cond2 === null ? null: false)
}
function runTests($cond1, $cond2, $expected) {
console.log($cond1, $cond2, $expected, $expected === testMyConditions($cond1, $cond2) ? '=> OK': '=> NOT OK')
}
runTests(true, true, true)
runTests(true, false, true)
runTests(true, null, true)
runTests(false, false, false)
runTests(false, null, null)
runTests(null, null, null)
I have a problem with a form check that use an if statement with multiple 'and' and 'or' operators. This check return me an anomalous occasionally false value.
public function insert_checkForm($form) {
$form = array_filter($form);
if (
!isset($form['report_id']) ||
!isset($form['date']) ||
!isset($form['technical_id']) ||
isset($form['travel_go_from']) != isset($form['travel_go_to']) ||
isset($form['work_go_from']) != isset($form['work_go_to']) ||
!isset($form['travel_go_from']) &&
!isset($form['travel_go_to']) &&
!isset($form['work_go_from']) &&
!isset($form['work_go_to'])
) {
return false;
} else {
return $form;
}
}
Last question, the above code changes compared to this (in spite of the priorities of and operators)?
[...]
!isset($form['report_id']) ||
!isset($form['date']) ||
!isset($form['technical_id']) ||
(isset($form['travel_go_from']) != isset($form['travel_go_to'])) ||
(isset($form['work_go_from']) != isset($form['work_go_to'])) ||
(!isset($form['travel_go_from']) && !isset($form['travel_go_to']) && !isset($form['work_go_from']) && !isset($form['work_go_to']))
[...]
Thanks =)
The most common problem with isset() is that it returns false when the item is NOT SET but also returns false if the item IS SET && IS NULL.
isset($arr['nonexisting']); //this returns: false
$arr['existing'] = null;
isset($arr['existing']); //this returns: false
This is the PHP code and I want to check if an invalid value is present:
$response = $_POST['response'];
$visibility = $_POST['visibility'];
if($response == NULL || $visibility == NULL ){
printf("Invalid input: %s\n", mysqli_connect_error());
echo "<br/><a href='myevents.php'>Back to previous page</a>";
exit();
}
$response and $visibility should be the integer value
so If people put the string value I want to go to the if($response == NULL || $visibility == NULL ) statement.
How to write the statement $response == ???
Using is_numeric will provide the desired result. is_numeric finds whether the given variable is numeric
if (!is_numeric($response) || is_numeric($visibility))
echo "Invalid input";
Some people suggest is_int(). Don’t use is_int(). Use is_numeric() instead.
Copy the following chunk of code into a php file and run it. You’ll be surprised at the outcome:
$t = "12345";
if( is_int($t ) ) {
echo $t . " is an int!";
} else {
echo $t . " is not an int!";
}
The problem is that is_int() thinks a string of numbers is a string, not an integer.
The key difference between the two is the one checks the type of variable, is_int(), and the other checks the value of the variable, is_numeric().
Can you try using is_nan() function,
if(is_nan($response) || is_nan($visibility)){
printf("Invalid input: %s\n", mysqli_connect_error());
echo "<br/><a href='myevents.php'>Back to previous page</a>";
exit();
}
var_dump(NAN == NAN); // boolean true
var_dump(NAN === NAN); // boolean true
var_dump(is_nan(NAN)); // boolean true
var_dump(NAN == 12); // boolean true
var_dump(NAN === 12); // boolean false
var_dump(is_nan(12)); // boolean false
var_dump(NAN == 12.4); // boolean true
var_dump(NAN === 12.4); // boolean true
var_dump(is_nan(12.4)); // boolean false
var_dump(NAN == NULL); // boolean true
var_dump(NAN === NULL); // boolean false
var_dump(is_nan(NULL)); // boolean false
var_dump(NAN == 'K<WNPO'); // boolean true
var_dump(NAN === 'K<WNPO'); // boolean false
var_dump(is_nan('K<WNPO')); // null and throws a warning "Warning: is_nan() expects parameter 1 to be double, string given in NANTest.php on line 13"
Ref: http://www.php.net/manual/en/function.is-nan.php
try is_numeric or is_int
Follow these links:
http://php.net/is_int
http://www.php.net/is_numeric
What does an exclamaton mark in front of a variable mean? And how is it being used in this piece of code?
EDIT: From the answers so far I suspect that I also should mention that this code is in a function where one of the parameters is $mytype ....would this be a way of checking if $mytype was passed? - Thanks to all of the responders so far.
$myclass = null;
if ($mytype == null && ($PAGE->pagetype <> 'site-index' && $PAGE->pagetype <>'admin-index')) {
return $myclass;
}
elseif ($mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
$myclass = ' active_tree_node';
return $myclass;
}
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}`
The exclamation mark in PHP means not:
if($var)
means if $var is not null or zero or false while
if(!$var)
means if $var IS null or zero or false.
Think of it as a query along the lines of:
select someColumn where id = 3
and
select someColumn where id != 3
! negates the value of whatever it's put in front of. So the code you've posted checks to see if the negated value of $mytype is == to null.
return true; //true
return !true; //false
return false; //false
return !false; //true
return (4 > 10); //false
return !(4 < 10); //true
return true == false; //false
return !true == false; //true
return true XOR true; //false
return !true XOR true; //true
return !true XOR true; //false
! before variable negates it's value
this statement is actually same as !$mytype since FALSE == NULL
!$mytype == null
statement will return TRUE if $mytype contains one of these:
TRUE
number other than zero
non-empty string
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}
The above !$mytype == null is so wrong. !$mytype means that if the variable evaluates to false or is null, then the condition will execute.
However the extra == null is unnecessary and is basically saying if (false == null) or if (null == null)
!$variable used with If condition to check variable is Null or Not
For example
if(!$var)
means if $var IS null.
I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false.
$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge) { ?>Stuff<?php } ?>
What's up?
This is broken because 'false' as a string will evaluate to true as a boolean.
However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent:
$canMerge = ($condition1 && $condition2);
The value of 'false' is true. You need to remove the quotes:
$canMerge = ($condition1 && $condition2) ? true : false;
Seems to me a reasonable question especially because of the discrepancy in the way PHP works.
For instance, the following code will output 'its false'
$a = '0';
if($a)
{
echo 'its true';
}
else
{
echo 'its false';
}
You are using 'true' and 'false' as string. Using a string(non-empty and not '0' and not ' ', because these are empty strings and will be assume as false) as a condition will results the condition to be true.
I will write some correct conditions that could be use:
$canMerge = ($condition1 && $condition2);
$canMerge = ($condition1 && $condition2) ? true : false;
$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge == 'true') { ?>Stuff<?php } ?>
$canMerge = ($condition1 && $condition2);
then
if ($canMerge){
echo "Stuff";
}