วันเสาร์ที่ 1 กรกฎาคม พ.ศ. 2560

การใช้ For Loops PHP (for,foreach)

ไม่มีความคิดเห็น
การใช้ For Loops PHP (for,foreach)
การใช้ for loops คือการวนข้อมูลเผื่อมาแสดงผล หรือนำข้อมูลบางอย่างไปใช้ในเรื่องของการ insert,update,delete ในดาต้าเบส (Database) อย่างไรก็แล้วแต่ PHP ก็มีตัวช่วยที่ทำให้นักพัฒนาสามารถนำไปใช้งานได้ วันนี้ผมจะขอยกตัวอย่างมา  2 ตัวช่วย
  1.  for loops
Syntax

for (init counter; test counter; increment counter) {
    code to be executed;
ตัวอย่าง
<?php
for ($start = 0; $start <= 20; $start++) {
    echo "The number of start: $start <br>";
}
?> 
ผลลัพธ์
The number of start: 0
The number of start: 1
The number of start: 2
The number of start: 3
The number of start: 4
The number of start: 5
The number of start: 6
The number of start: 7
The number of start: 8
The number of start: 9
The number of start: 10
The number of start: 11
The number of start: 12
The number of start: 13
The number of start: 14
The number of start: 15
The number of start: 16
The number of start: 17
The number of start: 18
The number of start: 19
The number of start: 20
for ซ้อน for 
 <?php
for ($start = 1; $start <= 10; $start++) {
$dot='';
for($i=1;$i<=$start;$i++){
$dot .= '.';
}
echo "$dot</br>";
}
?>

ผลลัพธ์
.
..
...
....
.....
......
.......
........
.........
..........
     2. foreach
foreach จะนิยมใช้ในการดึงข้อมูลที่เป็น Array ออกมา ตัวอย่างด้านล่าง

Syntax
foreach ($array as $value) {
    code to be executed; }
ตัวอย่าง 

 <?php
$gender = array("m", "f");
foreach ($gender as $value) {
    echo "$value <br>";
}
?> 
ผลลัพธ์
m
 อีกตัวอย่างการใช้ foreach ที่ข้อมูลใน Array มีลักษณะ Kay Value

ตัวอย่าง
 <?php
$gender = array("m"=>"Man", "f"=>"Female");
foreach ($gender as $key => $value) {
    echo "$key -> $value<br>";
}
?>
 ผลลัพธ์
m -> Man
f -> Female

ไม่มีความคิดเห็น :

แสดงความคิดเห็น