Question

I have written a basic HTML/PHP to calculate the Cayley table of some also basic binary operations over a finite set with n elements.

The filename is q.php and the code (cleaned of all styles, etc.) is the following:

<!doctype html>
<html>
<head><meta http-equiv="content-type" content="text/html;"></head>
<body>
<form action="q.php" method="post">
    Order:&nbsp;<input type="number" name="c1"><br><br>
    Operation:&nbsp;<input type="text" name="c2"><br>
    (syntax:<strong>&nbsp;$i "+" $j "%" 3&nbsp;</strong>)<br><br>
    <input type="submit" name="submit" value="Calculate / Reset">
</form>
<?php
$n=$_POST['c1']; $p=$_POST['c2'];
echo "<table style=\"text-align: center; margin: auto;\" cellpadding=\"8\">\n";
for ($i=0; $i<$n; $i++) {
    echo "<tr>\n";
    for ($j=0; $j<$n; $j++) {
        eval("\$a=\"$p\";");
        echo "\t<td>".$a."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>
</body>
</html>

It is very easy to input the integer n in the form, but (exactly as here) I can't find a good way to input in the form the binary operators (are they strings?).

More precisely, if the operation on i and j is e.g. i+(j mod 3), I would like to input sometinhg like

i + j % 3

or even

$i + $j % 3

instead of

$i "+" $j "%" 3

This latter with double quotes - not really enjoyable for the user - works already.

Can we do something better? And maybe also manage brackets (), to calculate (i+j)*2 as easily as i+(j*2) that I already do?

I'm now curious, thank you!

Was it helpful?

Solution

Try this

<?php
$n = $_POST['c1']; 
$p = trim(str_replace(' ', '', $_POST['c2'])); // Remove spaces


eval("\$result = {$p};");
echo $result;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top