php - Issue with factorial output
Get the solution ↓↓↓i wann to see factorial output from 1 to 10 . But for this i have to put print code 'echo' in loop . In out side of loop it is only showing factorial of 10 . here is my code . Help me to know why 'echo' is not working properly outside the loop.Thanks in advance for help.
$factorial = 1;
for ($n = 1; $n <= 10; $n++) {
$factorial *= $n;
echo "$factorial \n";
}
echo PHP_EOL;
$factorial = 1;
for ($n = 1; $n <= 10; $n++) {
$factorial *= $n;
}
echo "$factorial \n";
Answer
Solution:
Echo during looping will output each value during each iteration (that means the old data will be replaced by new ones). If you echo outside (below) the loop it will just display the value of the last iteration. To overcome your current problem you will need to capture all values into array and later print out in any way you require.
Your original code
$factorial = 1;
for ($n = 1; $n <= 10; $n++) {
$factorial *= $n;
}
echo "$factorial \n";
Try using array like this
$captureData = [];
$factorial = 1;
for ($n = 1; $n <= 10; $n++) {
$factorial *= $n;
$captureData[] = $factorial;
}
echo '<pre>';
print_r($captureData);
echo '</pre>';
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type bool in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.