I have a PHP function that is supposed return corresponding list of values for given input. Here is its code:
function output_values($s, $e, $d, $exp = '$i*$i') {
for($i = $s; $i <= $e; $i = $d) {
echo eval($exp);
// Put the value of $i in $exp and get the result.
}
}
The expression will always be mathematical like $i*$i
or 3*$i 8
etc.
I got the following error with it:
syntax error, unexpected end of file in eval()'d code
I know that I can use array_map()
. However, that function still requires me to pass the expression myself. In this case, I won't know the expression whose value I need to evaluate beforehand.
I hope I am making it clear.
Thanks.
CodePudding user response:
To pass an expression, or any code in general, use functions:
function output_values($s, $e, $d, callable $exp) {
for ($i = $s; $i <= $e; $i = $d) {
echo $exp($i);
}
}
output_values(1, 6, 2, fn ($i) => $i * $i);