PHP如何将循环迭代值存入数组?求解正确存储读取方法
Hey there! Let's clear up this confusion for you.
First off, your original code is actually working correctly to add all the loop values to the array—you just didn't check the whole array! When you do echo $array[0];, you're only looking at the first element (which is 0, since your loop starts at $i=0). If you use print_r($array); or var_dump($array); instead, you'll see every value from 0 to 10 is stored in the array.
But wait, you mentioned you need to store 1-10 instead of 0-10. That's an easy fix—just adjust the starting value of your loop from $i=0 to $i=1. Here's the corrected code:
$array = array(); for ($i=1; $i <= 10; $i++){ $array[] = $i; } // 查看整个数组的内容 print_r($array); // 或者取单个元素,比如第5个值(索引4,因为数组从0开始) echo $array[4]; // 输出5
Let me explain what $array[] = $i does: every time the loop runs, this line appends the current value of $i to the end of the array. So after the first iteration, $array has [1], after the second it has [1,2], and so on until it's [1,2,...,10].
If you prefer a while loop instead, here's how you'd write it to get the same result:
$array = array(); $i = 1; while ($i <= 10) { $array[] = $i; $i++; // 别忘记递增$i,否则会无限循环! } print_r($array);
The key takeaway here is that $array[] automatically adds new elements to the array, you don't have to manually set each index. Using print_r or var_dump is a great way to debug and see exactly what's in your array instead of checking just one element.
内容的提问来源于stack exchange,提问作者user9288465

