-2

Can I write code like below in php?

$operator = ">=90";
$val = 100;
if($val.$operator){
echo "Correct!";
}
  • have you tried? – jibsteroos Jun 29 '21 at 18:46
  • Check [this thread](https://stackoverflow.com/questions/2919190/dynamic-comparison-operators-in-php). It's not a strict duplicate (as the code you've shown is about evaluating expressions, and not just operators), but it might be worth taking a look over there. – raina77ow Jun 29 '21 at 18:46

1 Answers1

0

Look into the eval() function. Though, I would say you should look into closures and even arrow functions.

$operator = fn($x) => $x >= 90;
$val = 100;
if($operator($val)){
    echo "Correct!";
}
  • Here you have declared '>=90' manually, but I have variable which stores the '>=90' string. Above code will not work in my case. – Amol Borse Jun 30 '21 at 10:47
  • Read the link I provided about eval. Not sure what you are doing but I promise your are over complicating it. Explode the string if it is [dynamic and use a switch](https://stackoverflow.com/questions/2919190/dynamic-comparison-operators-in-php?noredirect=1&lq=1). @AmolBorse – Richard Tyler Miles Jul 01 '21 at 17:24