user398341
user398341

Reputation: 6577

PHP calculation based on the array values

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?

Upvotes: 1

Views: 163

Answers (1)

alex
alex

Reputation: 490213

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('+', '-', '/', '*'));
});

Upvotes: 2

Related Questions