1

I'm new to php and I would like to have a conditional statement like this:

if ($foo != 'Any') { $condition .= '$this_foo == $foo &&';}
if ($bar != 'Any') { $condition .= '$this_bar == $bar &&';}
if ($txt != 'Any') { $condition .= '$this_txt == $txt &&';}
$condition .= '$num1 > 0 && $num2 < 1000';

if (...[php would parse the $condition variable])
{
  someoperations
}

What is the proper syntax for the if statement to parse the variable $condition? So the conditional statement depends on the other variables and to prevent a long nested conditional statement.

Thanks in advance!

2 Answers 2

2

Well it's not exactly parsing, but you could evaluate your condition as the code is executed.

$condition = true;
if ($foo != 'Any') { $condition = $condition && ($this_foo == $foo);}
if ($bar != 'Any') { $condition = $condition && ($this_bar == $bar);}
if ($txt != 'Any') { $condition = $condition && ($this_txt == $txt);}
$condition = $condition && ($num1 > 0 && $num2 < 1000);

if ($condition)
{
  someoperations
}

So let's say that $foo != 'Any' is true, that would result in

$condition = true && ($this_foo == $foo) && ($num1 > 0 && $num2 < 1000);

Let's pretend $this_foo == $foo, $num1 == 45 and $num2 == 2300

$condition = true && true && (true && false);
$condition = false;

and your if won't execute.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for this! it helped me. I'll upvote this when I have the reputation.
there we go. I only joined here yesterday so I'm a newbie. =)
0

I believe what you want is

if (eval("return " . $condition)) {...}

Making sure to check for the FALSE case if the parsing fails.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.