0

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

softboxkid
  • 877
  • 6
  • 13
  • 31

3 Answers3

0

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++) {
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
  • Um, I don't see what the difference is between both lines of code. Or, have I missed something? Oh wait... as I was typing this, I kept staring at what was different and then it suddenly hit me after about a minute. It was the added `=` (equal) sign. *That* should have been part of the answer. Others might also not pick it up so quickly. Please edit it. My comment stands to not be reliable later on, as it could disappear without any advance notice. – Funk Forty Niner Nov 01 '19 at 00:17
  • Edited as per @FunkFortyNiner concern – Anatoliy R Nov 01 '19 at 00:24
0

You need to use < instead of <= in your for loop.

And you can do it a more simple way,

$result = 0;
for($i = 0; $i < 6; $i++){
    $result += $string[-$i];
}
LF00
  • 27,015
  • 29
  • 156
  • 295
0

An alternative method without loops (or error checking, for what it's worth):

function accountHash($accountNumber)
{
    return array_sum(
        preg_split('//u', mb_substr($accountNumber, -6), null, PREG_SPLIT_NO_EMPTY)
    );
}

Demo

Álvaro González
  • 142,137
  • 41
  • 261
  • 360