2

I'm passing the comparison operator as a variable to the PHP Cli:

./test.php -k "command" -c ">0"

The command in -k products a result and I've stored it in $result

The problem I'm getting is I want to pass the logic and comparison operator as variables, is this possible?

$result = 2;
$logic = ' >0';

if ( $result $logic ) echo "true"; 

But I get:

PHP Parse error: syntax error, unexpected '$logic' (T_VARIABLE)

Any ideas?

locke14
  • 1,335
  • 3
  • 15
  • 36
trevrobwhite
  • 443
  • 1
  • 7
  • 22
  • 1
    you can use `eval()` - but it's a safety flaw - see here https://stackoverflow.com/questions/41406/how-do-i-execute-php-that-is-stored-in-a-mysql-database – treyBake Jul 05 '19 at 12:59
  • If `-c` has not many options it's better to use `switch` instead `eval`. – u_mulder Jul 05 '19 at 13:04

3 Answers3

2

It's not possible to do it that way, but you can do it using the eval method, like this:

$result = 2;
$logic = ' >0';


eval('$logicResult = ' . $result . $logic .';');
if ( $logicResult ) echo "true"; 

The eval method is not recommended, as it might introduce security flaws in your app.

Claudio
  • 5,078
  • 1
  • 22
  • 33
2

While eval does the trick, it is generally considered harmful.

If the universe of possible operator instances in $logic is limited, better work with a switch statement or a cascaded if:

$result = 2;
$logic = trim(' <0');

$op2 = substr($logic, 0, 2);
$op1 = substr($logic, 0, 1);

if ( $op2 == '>=') {
  $operand = substr($logic, 2);
  if ($result >= (int)$operand) { echo "true"; } 
} elseif ( $op1 == '>' ) {
  $operand = substr($logic, 1);
  if ($result > (int)$operand) { echo "true"; } 
} elseif ( $op1 == '=' ) {
  $operand = substr($logic, 1);
  if ($result == (int)$operand) { echo "true"; } 
} elseif ( $op2 == '<=') {
  $operand = substr($logic, 2);
  if ($result <= (int)$operand) { echo "true"; } 
} elseif ( $op1 == '<' ) {
  $operand = substr($logic, 1);
  if ($result < (int)$operand) { echo "true"; } 
} else {
  echo "operator unknown: '$logic'";
}
collapsar
  • 17,010
  • 4
  • 35
  • 61
1

As @treyBake notice, you can use eval() - Evaluate a string as PHP code:

<?php

$result = 2;
$logic = 'if(' . $result . '>0){echo "true";};';
eval($logic);
MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46