[SOLVED]Using the value of variable in the php code...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
dhrosti
Forum Commoner
Posts: 90
Joined: Wed Jan 10, 2007 5:01 am
Location: Leeds, UK

[SOLVED]Using the value of variable in the php code...

Post by dhrosti »

I'm trying to build a simple calculator in php and I have realised that I may need lots of switch statements which I cant really be bothered to do (It is Friday afternoon, after all). So i was wondering if it was possible to use the value of a variable, such as a plus sign (+) in an expression?
Last edited by dhrosti on Fri Mar 09, 2007 10:14 am, edited 1 time in total.
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

If you use the variable to construct the operation as a string, eval() could be used to evaluate it.
User avatar
dhrosti
Forum Commoner
Posts: 90
Joined: Wed Jan 10, 2007 5:01 am
Location: Leeds, UK

Post by dhrosti »

Im getting on better then i was, however its not wanting to work for me...

Code: Select all

function execute($query) {
	
	$query2 = addslashes($query).";";
	
	$val = eval($query2);
	
	return $query." = ".$val;

}
For example if I were to use "3 + 7" as a query, it should execute the query as if it were part of the php code and return "3 + 7 = 10". Im getting nothing for $val at the moment though.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

What's with the call to addslashes()?

The call to eval() should have "return" in it to receive the output of the expression.
User avatar
dhrosti
Forum Commoner
Posts: 90
Joined: Wed Jan 10, 2007 5:01 am
Location: Leeds, UK

Post by dhrosti »

Works now, thanks.
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

I wouldn't stick that script on a public server -- someone might hax0r your internets.
Post Reply