Pregunta

I am having some problems with PHP.

I used while to sum a number's digits always that it has more than two digits, some how, it gets into an infinity loop. e.g: 56 = 5 + 6 = 11 = 1+1= 2.

Here is the code:

$somaP = 0;

$numPer = (string)$numPer; //$numPer = number calculated previously

while (strlen($numPer) > 1){
    for ($j = 0; $j < strlen($numPer); $j++){
        $somaP = $somaP + (int)($numPer[$j]);
    }
    $numPer = (string) $somaP;
}

Can anyone help me? Guess it is a simple mistake, but I couldn't fix it.

¿Fue útil?

Solución

You need to reset the value of $somaP in your while loop.

Currently it continues to increase its value every time through the loop.

Try this:

$numPer = (string)$numPer; //$numPer = number calculated previously

while (strlen($numPer) > 1){
    $somaP = 0;
    for ($j = 0; $j < strlen($numPer); $j++){
        $somaP = $somaP + (int)($numPer[$j]);
    }
    $numPer = (string) $somaP;
}

Otros consejos

Take a look at this line:

 $numPer = (string) $somaP;

It seems that the length of $somaP is never lesser (or equal) than 1. So the length of $numPer is never lesser (or equal) than 1.

What are you trying to do? It's unclear to me.

This for example would add every number in a string together?

E.g "1234" = 1+2+3+4 = 10

 $total = 0;
 for($i = 0; i < strlen($string); $i++){
        $total += $string[$i];
 }
 echo $total;

This looks cleaner I would say:

$numPer = 56;
while ($numPer > 9){
    $numPer = array_sum(str_split($numPer));
}
echo $numPer;

PHP handles all string <> number conversions for you, so no need to do (string) on a number unless really needed.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top