Add
{code} {code} == == * * _ _ [] * #

Add arbitrary numbers

2017-02-13 18:18:23

function add($a, $b) {
    $r = '';
    $a = str_split(strrev($a));
    $b = str_split(strrev($b));
    if (count($b) > count($a)) {
        $tmp = $a;
        $a = $b;
        $b = $tmp;
    }
    for ($carry = 0, $idx = 0; isset($a[$idx]) || $carry; $idx++) {
        $value = (int)($a[$idx] ?? 0) + (int)($b[$idx] ?? 0) + $carry;
        if ($carry = (int)($value > 9)) $value -= 10;
        $r .= $value;
    }
    return strrev($r);
}