0

## PHP 陣列和迴圈應用一問

foreach (陣列名稱//讀完所有資料){

for (每次執行兩次)

echo "第一筆、第二筆" 下次是 "第三筆、第四筆"

}

```\$array = array("1","2","3","4","5","6","7","8","9");
for(\$i=1; \$i<count(\$array); \$i+=2) {
//認真一點的話,這裡要判斷 \$i <= count(\$array)-1 以免 index out of bound
echo \$array[\$i]."--".\$array[\$i+1];
}
```
sunallen iT邦好手 1 級 ‧ 2015-06-04 20:26:39 檢舉

sunallen iT邦好手 1 級 ‧ 2015-06-06 22:43:28 檢舉

### 2 個回答

2
vic0322man
iT邦新手 5 級 ‧ 2015-06-05 17:38:15

``````&lt;pre class="c" name="code">

\$a = [1,2,3,4,5,6,7,8,9];
for( \$j=0; \$j&lt;=count(\$a); \$j+=2)
{
if(!empty(\$a[\$j]))
echo \$a[\$j];
\$i = \$j+1;
if(!empty(\$a[\$i]))
echo \$a[\$i];
}
``````
0
weiclin
iT邦高手 7 級 ‧ 2015-06-05 09:21:07

``````&lt;pre class="c" name="code">
\$a = [1,2,3,4,5,6,7,8,9];
echo "----\n";
while(\$a){
echo array_shift(\$a), "\n";
if(\$a) echo array_shift(\$a), "\n";
echo "----\n";
}

echo "\n----\n";
\$a = [1,2,3,4,5,6,7,8,9];
foreach(array_chunk(\$a, 2) as \$part){
foreach(\$part as \$element){
echo \$element, "\n";
}
echo "----\n";
}
``````
sunallen iT邦好手 1 級 ‧ 2015-06-06 22:42:32 檢舉