Sam Samson
Sam Samson

Reputation: 947

How to convert string to boolean in php

I've defined this function in php

function ifstatement($statement = 'if(10 > 9;1+1;2+2)') {
// $statement = str_replace(' ', '', $statement);

if (strpos($statement, 'if(') > -1) {
   $statement = rtrim(ltrim(str_replace(' ', '', $statement), 'if('), ')');
   $exp = explode(';', $statement);
  if ( $exp[0] ) {
    if (strpos($exp[1], 'if(' )> -1) {
     return ifstatement($exp[1]);
    } else {
     return 1;
   }
  } else {
  if (strpos($exp[2], 'if(')> -1) {
    return ifstatement($exp[2]);
  } else {
   return 0;
  }
 }
}else{
  echo 'out';
  }
}

the problem is the function always return 1 even if the condition in the if statement in the function argument is false which is tested with

if($exp[0])

it looks like the $exp[0] comes as a string, how can i convent this to be tested as if argument

Upvotes: 0

Views: 252

Answers (3)

Brad Mace
Brad Mace

Reputation: 27916

Unless you're going to do this properly (with a parser), you're better off making users specify their conditions in multiple fields. One row would have a text field for x, a select field for comparison operator (==,<,>), and another text field for y. Then they can specify whether to match all checks or any checks. When they're broken out like this you'll be able to execute the intended logic without having to implement a new language using strpos and eval, which is total madness.

You can see examples of this type of interface in Thunderbird's message filter editing:

enter image description here

and in iTune's smart playlist editing:

enter image description here

Upvotes: 0

piotrp
piotrp

Reputation: 3874

$exp[0] contains 10 > 9 (whatever you have before first ;), so it will evaluate to false only it it's an empty string or '0'. To properly evaluate this you should use the eval() function:

$condition = '10 > 9';
$result = eval('return ' . $condition . ';');

Note: don't ever use eval() in production environment unless you are really sure that your input is harmless and you can't do it another way.

Upvotes: 2

genesis
genesis

Reputation: 50982

$exp[0] = (boolean) $exp[0];

is probably the thing you're looking for

Upvotes: 0

Related Questions