1

I'm trying to create a calculation based on the values of the array - imagine the following array:

$values = array(9, +, 10, *, 7)

I thought about the following approach:

$result = number_format(implode(' ', $values), 2)

but this obviously doesn't work.

Any idea how could this be achieved?

1

1 Answer 1

2

You could use eval()...

eval('$result = ' . implode($values) . ';');

If any portion of this array came from user input, you should filter the array to ensure it only has numbers and valid operators.

$safeValues = array_filter($values, function($value) {
    return is_numeric($value) OR in_array($value, array('+', '-', '/', '*'));
});
Sign up to request clarification or add additional context in comments.

5 Comments

agreed, although depending on your hosting this may be restricted. If you can't use the eval method, you're likely going to need to create a math parser, or find a library that will do so
or something like eval('$result = ' . implode($values) . ';'); since eval returns null usually.. and the expression does not return something, so you need to assign the result in the variable inside the eval call
@mishu Thanks, I haven't used PHP in a little while :)
@alex you are welcome.. it was just a small note, I think everyone got the idea.. as this one: you might want to add a semicolon also at the end of the line (just after implode) :)
@mishu I'm hopeless tonight :P Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.