PHP calculate

15.Jul.2010

My friend asked me couple a days ago, how to make a sort of calculator for his client. Client should be able to type full formula to input field (something like “(3*2/6+4)*1.1”), and his website should output the data. So I came up with a simple PHP calculate function in order to make it easy for them and here it is. A simple PHP calculate function:

1
2
3
4
5
6
7
8
function calculate($formula) {
	try {
		eval('$result = ' . $formula . ';');
		return $result;
	} catch (Exception $e) {
		return false;
	}
}