1

i already looked in the existing questions but nothing was close to my situation.

I would like to express a condition inside a variable. The problem is that if I use:

if($condition) {

it is true if $condition has a value, while i would like to make it true if the content of the variable is true:

$condition = “$a < 3”;
if($condition) {

The idea is that I store the conditions in the database, and I use them inside a while() according to the situation. I don’t know if I was clear, sorry if I wasn’t.

Hope you got the question, and thanks in advance!

2 Answers2

2

It seems you are looking for php eval https://www.php.net/manual/en/function.eval.php

$test = 'return $a < 3;';
$test2 = 'return $a < 1;';

$a = 2;

if (eval($test)) {
    echo 'a < 3 ';
} else {
    echo 'a > 3 ';
}


if (eval($test2)) {
    echo 'a < 1 ';
} else {
    echo 'a > 1 ';
}

prints a < 3 a > 1

Be careful because $test = "return $a < 3;"; would not compile as the var $a is not defined at that point so you should use single quotes so that its content is not interpreted.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
0

$condition = ‘$_POST[‘abc’] == “xyz”’; In this line you are using single inverted comma which will make it string $condition = $_POST[‘abc’] == “xyz"; This will return boolean.

Rudra
  • 704
  • 8
  • 16
  • @TranslationsCloud oh, Sorry I think this link may help https://stackoverflow.com/questions/52315387/evaluate-string-as-condition-php – Rudra Mar 08 '20 at 12:40