[PHP_Day 6]_基本語法part6_迴圈for_foreach



for loop 跟 foreach寫法


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
 $arr = ["張三","李四","王五"];
 #$count = count($arr);
 #echo $count."<br/>";
 echo "=======while loop======<br/>";
 $idx = 0;
 while($idx < count($arr)){
  echo "名字:[".$idx."]".$arr[$idx]."<br/>";
  $idx++;
 }
 echo "=======for loop======<br/>";
 for($idx2 = 0; $idx2 < count($arr) ; $idx2++){
  echo "名字:[".$idx2."]".$arr[$idx2]."<br/>";
 }
 echo "=======for v.s. foreach ======<br/>";
 echo "=======for======<br/>";
 $Students = [
  [
   "name" => "小明",
   "數學成績" => 80
  ],
  [
   "name" => "小菲",
   "數學成績" => 87
  ],
  [
   "name" => "小李",
   "數學成績" => 93
  ],
 ];
 for($idx3 = 0; $idx3 < count($Students) ; $idx3++){
  $student = $Students[$idx3];
  echo "姓名:".$student["name"]."<br/>";
  echo "數學成績:".$student["數學成績"]."<br/>";
 }
 echo "=======foreach======<br/>";
 foreach($Students as $student){
  echo "姓名:".$student["name"]."<br/>";
  echo "數學成績:".$student["數學成績"]."<br/>";
 }
 
?>








留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題