Search code examples
phpsubstr

PHP sum last 6 digit from substring


I'm trying to adding all numbers from last 6 digit from substr(). Let say the number is 19283774616, I'm trying to have result from this: 7+7+4+6+1+6 = ?. Here is my current code

public function accountHash($accountNumber)
{
    $result = 0;
    $accountNumber = substr($accountNumber, -6);

    for($i=0; $i<=strlen($accountNumber); $i++) {
        $result += substr($accountNumber, $i, 1); // A non-numeric value encountered here
    }

    echo $result;

}

From the function above, "A non-numeric value encountered" error occurred. Need suggestion on how to do this. Thank you


Solution

  • You attempt to get more characters than string contains. Replace "<=" with "<" in your condition expression, i.e. change:

    for($i=0; $i<=strlen($accountNumber); $i++) {
    

    to

    for($i=0; $i<strlen($accountNumber); $i++) {