-1
$gted = (object)'>';
if(200 $gted 300){
    echo 'wow it worked';
}else{
    echo 'no it didnt work';
}

I am trying to convert the '>' to a conditional > to use in an if statement. Thanks.

1 Answers1

3

This will not work the way that you have it. Variables cannot be be interpreted as operators in PHP directly, see also this question.

Even if you could interpret a variable as an operator, what you have in your string 'object' is not a greater-than sign, it is an HTML entity that, when interpreted as an HTML entity, yields something that looks like a greater-than sign.

This question has some answers that include some workarounds for arithmetic operators which can be used to store results to be evaluated inside of an if statement. As an example for use in this answer, I borrowed and slightly modified part of this answer by @user187291 that uses create_function:

$operator = '+';
$func = create_function('$a,$b', "return \$a $operator \$b;");

$result = $func(5, 1);
echo $result;

The echo'd result would be 6, as you would expect. You could change what operator is being used so that the pseudo-anonymous function instead returns a boolean value which you could then plug into an if statement:

$operator = '>';
$func = create_function('$a,$b', "return \$a $operator \$b;");

$result = $func(200, 300);
if($result) {
    echo 'wow it worked';
} else {
    echo 'no it didnt work';
}

Except in extreme and very specific circumstances that I cannot currently imagine, I would not think this to be a good idea.

Community
  • 1
  • 1
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96