When to use while loop in PHP

Notes:

When to use while loop rather than for loop:
- When we know exactly how many number of times the loop need to be executed, then we use for loop.
- When we do not know exactly how many number of times the loop need to be executed, then we use while loop.

PHP script to compute the sum of digits in a given Integer:
Ex: 12, 123, 1234, 12345, etc.

PHP script to find sum of digits in a given integer without a loop:

$num=123;
$lastDigit=0;
$sumOfAllDigits=0;

$lastDigit = $num % 10; // 3
$sumOfAllDigits = $sumOfAllDigits + $lastDigit; // 3
$num = (int)($num/10); // 12

$lastDigit = $num % 10; // 2
$sumOfAllDigits = $sumOfAllDigits + $lastDigit; // 5
$num = (int)($num/10); // 1

$lastDigit = $num % 10; // 1
$sumOfAllDigits = $sumOfAllDigits + $lastDigit; // 6
$num = (int)($num/10); // 0

echo "sumOfAllDigits=",$sumOfAllDigits;

PHP script to find sum of digits in a given integer using while loop:

$num = 12;
$lastDigit=0;
$sumOfAllDigits=0;

while($num != 0)
{
$lastDigit = $num % 10;
$sumOfAllDigits = $sumOfAllDigits + $lastDigit ;
$num = (int )($num / 10);
}
echo "sumOfAllDigits=",$sumOfAllDigits;

Interview Questions:

1. PHP stands for ______________
a. Hypertext Preprocessor
b. Preprocessor Hypertext
c. Personal Home Processor
d. Personal Hypertext processor
Ans: a