Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $numbers = array(5, 19, 45, 6, 7, 21);
- $operators = array('*', '+', '-', '*', '+');
- function rechne($numbers, $operators) {
- $numbers[0] = array(0, '+', $numbers[0]);
- foreach ($operators as $op) {
- $left = array_shift($numbers);
- $right = array_shift($numbers);
- if (in_array($op, array('+', '-'))) {
- array_unshift($numbers, array($left, $op, $right));
- } else {
- $left[2] = array($left[2], $op, $right);
- array_unshift($numbers, $left);
- }
- }
- return rechne_helper($numbers[0]);
- }
- function rechne_helper ($struct) {
- if (!is_array($struct)) {
- return $struct;
- }
- $left = rechne_helper($struct[0]);
- $right = rechne_helper($struct[2]);
- switch ($struct[1]) {
- case '+':
- return $left + $right;
- break;
- case'-':
- return $left - $right;
- break;
- case '*':
- return $left * $right;
- break;
- }
- }
- echo rechne($numbers, $operators);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement