• 0

[PHP] Set a dynamic Equation as a function


Question

I'm not sure how to do this in php, but what I want to be able to do is have a user input an equation such as "x^2 + 2x -1" in a text box. Then I want to be able to store that as something like function f(), essentially f(x).

Then I want to be able to call something like f(1) and get it to process the function entered, which was stored as f(), using 1 as the x value.

Does anyone have an idea of how to do this?

5 answers to this question

Recommended Posts

  • 0

Doing such a thing directly in PHP would likely be impractical for the application. I would look into passing such an argument to an external program and having its results returned to the user via PHP.

Is "Octave" available on your system?

break the input string apart and put it into operators that you could rewrite into an octave script using various regular expressions and string functions. That looks almost exactly like what octave will take as input anyway. Then execute octave with the user parameter (i.e., f(1)) and return the outputted results to the user.

Actually, I want to see if this works now.

You may also find something useful over in the Math section of PEAR.

  • 0

Note you should do some additional checks to the input string but you can do something like that with this code:

<?php
session_start();
$equation = $_SESSION['equation'];

if( !empty( $_POST['submit'] ) ) {
	switch( $_POST['submit'] ) {
	case 'store equation':
		$equation = $_POST['equation'];
		// save equation
		$_SESSION['equation'] = $equation;
		break;
	case 'calculate f(x)':
		$x = $_POST['x'];
		$param = $x;
		$equation2 = str_replace( "x", "\$param", $equation ); // replace every instance of x to a parameter
		$result = eval( $equation2 );
		break;
	}
}
?>
<?php if( !empty( $result ) ) echo "<h2>" . $result . "</h2>"; ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php if( $equation == "" ) { ?>
<input type="text" name="equation" value="">
<input type="submit" name="submit" value="store equation">
<?php } else { ?>
<h3><?php echo $equation; ?></h3>
<input type="text" value="x" value="<?php echo $x; ?>">
<input type="submit" name="submit" value="calculate f(x)">
<?php } ?>
</form>

test with 2 * x + ( 1 + x ) or with any equation

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.