3

How can I calculate values in a string containing the following numbers and (+/-) operators:

Code Like

$string = "3+5+3-7+4-3-1"; 

//result should be = 4

Updated: I am trying to calculate $array = [1, +, 6, -, 43, +, 10];

I have converted into the string: implode("", $array);

3 Answers3

1

you can use eval

$string = "3+5+3-7+4-3-1"; 
eval( '$res = (' . $string . ');' );
echo $res;
sami
  • 36
  • 3
0
$arr_val = array(1, '+', 6, '-', 43, '+', 10);
$total = 0;

if(isset($arr_val[0]) && ($arr_val[0] != '+' || $arr_val[0] != '-'))
    $total = intval($arr_val[0]);

foreach($arr_val AS $key => $val) {
    if($val == '+') {
        if(isset($arr_val[$key+1]) && ($arr_val[$key+1] != '+' || $arr_val[$key+1] != '-')) {
            $total = $total + intval($arr_val[$key+1]);
        }
    } else if($val == '-') {
        if(isset($arr_val[$key+1]) && ($arr_val[$key+1] != '+' || $arr_val[$key+1] != '-')) {
            $total = $total - intval($arr_val[$key+1]);
        }
    }
}

echo $total;

May be it will solve your problem.

Rahul Tank
  • 130
  • 1
  • 8
0

For any kind of array like: [1, + , 4, -, 5, , 3, 8, + , 6]

Solved with the custom php helper function:

function calcArray($arrVal) 
{
    if (count($arrVal) == 1) {
        return reset($arrVal);
    }

    if (is_int($arrVal[1])) {
        $arrVal[0] = $arrVal[0].$arrVal[1];

        unset($arrVal[1]);

        return calcArray(array_values($arrVal)); 
    }

    $emptyValKey = array_search('', $arrVal);

    if ($emptyValKey) {
        $concatVal = $arrVal[$emptyValKey-1].$arrVal[$emptyValKey+1];

        unset($arrVal[$emptyValKey+1]);
        unset($arrVal[$emptyValKey]);

        $arrVal[$emptyValKey-1] = $concatVal;

        return calcArray(array_values($arrVal));
    }

    $total = $arrVal[1] == "+" ? $arrVal[0] + $arrVal[2]:$arrVal[0] - $arrVal[2];

    unset($arrVal[0]);
    unset($arrVal[1]);
    unset($arrVal[2]);

    array_unshift($arrVal, $total);

    $arrVal = array_values(array_filter($arrVal));

    return calcArray($arrVal);
}