Advertisement
Guest User

Untitled

a guest
May 30th, 2011
548
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.04 KB | None | 0 0
  1. <?php
  2.  
  3. $numbers = array(5, 19, 45, 6, 7, 21);
  4. $operators = array('*', '+', '-', '*', '+');
  5.  
  6.  
  7. function rechne($numbers, $operators) {
  8.     $numbers[0] = array(0, '+', $numbers[0]);
  9.     foreach ($operators as $op) {
  10.         $left = array_shift($numbers);
  11.         $right = array_shift($numbers);
  12.         if (in_array($op, array('+', '-'))) {
  13.             array_unshift($numbers, array($left, $op, $right));
  14.         } else {
  15.             $left[2] = array($left[2], $op, $right);
  16.             array_unshift($numbers, $left);
  17.         }
  18.     }
  19.  
  20.     return rechne_helper($numbers[0]);
  21. }
  22.  
  23. function rechne_helper ($struct) {
  24.     if (!is_array($struct)) {
  25.         return $struct;
  26.     }
  27.  
  28.     $left = rechne_helper($struct[0]);
  29.     $right = rechne_helper($struct[2]);
  30.     switch ($struct[1]) {
  31.         case '+':
  32.             return $left + $right;
  33.         break;
  34.         case'-':
  35.             return $left - $right;
  36.         break;
  37.         case '*':
  38.             return $left * $right;
  39.         break;
  40.     }
  41. }
  42.  
  43. echo rechne($numbers, $operators);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement