Reputation: 83
I have a dynamic array.
Lets suppose
array (size=3)
0 => string '20' (length=2)
1 => string '-' (length=1)
2 => string '5' (length=1)
its result will be 20-5 = 5
Array size is not defined , how can i solve it dynamically ?
Upvotes: 0
Views: 170
Reputation: 583
You can use following code. Of course, it have some limitations. Depends on what you want to do and why you are doing it.
<?php
$array = array(
'20',
'-',
'5',
'*',
'10'
);
$output = null;
$symbol = null;
foreach ($array as $item) {
if ($item == '+' || $item == '-' || $item == '*' || $item == '/') {
if ($output === null) {
die("First item should be numeric! ");
}
$symbol = $item;
continue;
} elseif (!is_numeric($item)) {
die("unknown symbol: " . $item);
}
// is numeric
// first symbol
if ($output == null) {
$output = $item;
continue;
}
if ($symbol === null) {
die('Two numbers in a row!!');
}
switch ($symbol) {
case '+':
$output += $item;
break;
case '-':
$output -= $item;
break;
case '*':
$output *= $item;
break;
case '/':
$output /= $item;
break;
}
}
echo "Calculation is: " . $output;
Upvotes: 2
Reputation: 8855
One of the few cases where phps most hated and feared function comes in handy.
The evil eval()
:
$input = array('20', '-', '5');
// build formula from array by glueing values together
$formula = implode(' ', $input);
// execute the formula and store result in $result
eval('$result = ' . $formula . ';');
// voila!
echo $formula . ' = ' . $result;
The nice thing about using eval()
is that you can use all mathematical operations known in php and even handling of brackets is fully supported.
Visit http://sandbox.onlinephpfunctions.com/code/71ffc94238a5510cd7b24632fc7a8b9b5cb2c2c0 for a working example with more formulas defined for testing.
Upvotes: 1