Log in

View Full Version : Dynamic operators in if conditionals



Aphex_
05-16-2006, 11:17 PM
I am attempting to make an operator in an if conditional
a variable like so:

$x=1;
$y=2;
$operator='!=';

if ($x $operator $y) {
echo "Not equal!\n";
}

But obviously that doesnt work.
Is it possible to convert a string to an operator?
Any help would be appreciated.

Thanks,

Aphex_

djr33
05-17-2006, 06:10 AM
I don't mean to distract from your particular question, but this has bugged me for some time.

In specific situations, it's nice to have variables actually change the php code itself.

For example, it would be helpful if you could get a chunk of php from an outside source, like a database, depending on the situation.

This operator question is a good example of it.

At one point, I was playing around with a user-submitted math function (form with a text box they could enter "x+1" and expect a resulting set of numbers).
But... didn't work, because I never was able to figure out how to set it up so that the input worked as math. I suppose with complex enough if statements and loops, I could use php to interpret the input, finding the various symbols and such, but that would be a lot of work.


Unless someone knows something more, I think the best way to solve your problem if to just use a bunch of manually coded if statements.

if ($operator == "!=" && $x != $y) {
//do stuff
}

Then repeat for each possibility.



So... anyone know if you CAN control the actual php script within itself?

Aphex_
05-17-2006, 06:10 AM
I got this working using the eval() function after someone suggested it to me.

Thanks.

djr33
05-17-2006, 06:11 AM
Ah. Good.

I am still very interested in the concept, though.

It's a worthwhile thing to look into for other uses.

Glad its working :)

Twey
05-17-2006, 06:36 AM
Yes... the eval (http://uk.php.net/eval)() function. The boon and curse of interpreted languages.

It should almost never be necessary to use it.

And you've made the newbie's mistake and confused = with ==. :)

djr33
05-17-2006, 06:53 AM
Ah, thanks. Fixed the = thing... I'm tired.

Will look into eval.