Ajay Varma
Ajay Varma

Reputation: 17

How can I use a variable as an operator?

I would like code 1 to work the same as code 2, but it doesn't.

<?php
//code 1
$z = '>';
$v = 50;
$a1[0] = 60;

if($v .$z. $a1[0])
{
    echo "<td>" . "test" . "</td>";
} else {}

//code 2
if($v > $a1[0]){
    echo "<td>" . "test" . "</td>";
} else {}

In the above code I want to replace the > symbol with a variable so that I can make it dynamic.

How can I do this?

Upvotes: 1

Views: 156

Answers (1)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

Basically, you can't use a variable as an operator in PHP.

All that the $v .$z. $a1[0] expression does is concatenate the variables together into a string.

I think the closest you'd be able to get to being able to use a "dynamic operator" would be to define an array of operations that you could select from using your variable.

$ops = [
    '>' => function($a, $b) { return $a > $b; },
    '<' => function($a, $b) { return $a < $b; },
    '=' => function($a, $b) { return $a == $b; }
];

$z = '>';

$v = 50;

$a1[0] = 60;

if ($ops[$z]($v, $a1[0])) {
    echo "<td>" . "test" . "</td>";
}

(Keep in mind that with your example values, $v is not greater than $a1[0], so this example won't echo anything.)


Regarding eval, since it was mentioned a couple of times in the comments on your question, most people advise against using it, for good reasons. There is almost always a better way to solve your problem.

Upvotes: 6

Related Questions