Skip to content
Advertisement

PHP Recursively calculate a formula in an array in reverse

I would like te perform a calculation on the following array

$array = [
    "calculation" => [
        "add" => [
            "ceil" => [
                "multiply" => [
                    9.95,
                    "90%"
                ]
            ],
            0.95
        ]
    ]
];

eventually the calculation would traverse into:

1. add(ceil(multiply(9.95, 90%)), 0.95)
2. ceil(multiply(9.95, 90%)) + 0.95
3. ceil(8.955) + 0.95
4. 9 + 0.95
5. 9.95

I’ve tried recursively looping through the array using array_walk_recursive and custom functions which basically to the same. but the problem is that the add cannot calculate the ceil before it has calculated the multiply.

So how can i recusively in reversed order calculate all the parts of the array?

I’m slowly loosing my mind over this and starting to question if it’s even possible.

All ideas are greatly appreciated

Advertisement

Answer

Assuming that you have this structure, you may use this code. If you need more than 2 values to be “added” or “multiplied” you may need to use some splat operator or change the logic a little bit:

<?php

$array = [
    "calculation" => [
        "add" => [
            "ceil" => [
                "multiply" => [
                    9.95,
                    "90%"
                ]
            ],
            0.95
        ]
    ]
];

function add($a, $b) {
    return $a + $b;
}

function multiply($a, $b) {
    return $a * $b;
}

function calculation($arr, $operation = null) {
    
    $elements = [];
    
    foreach($arr as $k => $value) {
        if (is_numeric($k)) {
            // change % with valid numeric value
            if(strpos($value, '%')) {
                $value = str_replace('%','',$value) / 100;
            }
            //if there are no operations, append to array to evaluate under the operation
            $elements[] = $value;
        } else {
            //if there are operations, call the function recursively
            $elements[] = calculation($value, $k);
        }
    }

    if ($operation !== null) {
        return call_user_func_array($operation, $elements);
    }
    return $elements[0];
}

echo calculation($array['calculation']);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement