php - I have some problems in getting the logic of a program -


i have following codes reverse number:

<?php      function reverse_num($num){         $sum = 0;         while(floor($num)){             $newnum = $num%10;             $sum = $sum * 10 + $newnum;             $num = $num/10;         }         return $sum;     }     echo reverse_num(98);     ?> 

in code, when loop first time initialized, returning 8 value of $sum. wanted know storing value? changing value of $sum(above while loop) 0 8? give me rough sketch storing sum returned first time? question whether value of $sum initialized 0 on top remains same or changes because whenever echo $sum on top, show 0. can not directly see whether changing or not?

edit: okay say?(see comments):

<?php      function reverse_num($num){         $sum = 0; //logically becomes $sum = 8; oaky say?         while(floor($num)){             $newnum = $num%10;             $sum = $sum * 10 + $newnum;             $num = $num/10;         }         return $sum;     }     echo reverse_num(98);     ?> 

the value of $sum is changing in loop. before loop it's initialised 0 ($sum = 0). when loop runs, value of $sum changed value of $sum * 10 + $newnum each iteration of loop.

the loop returns 8 first time (going through code):

  1. $newnum = 8 (98 % 10 = 8)
  2. $sum = 8 ((0 * 10) + 8 = 8)

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -