-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7-Loops.php
More file actions
87 lines (87 loc) · 2.6 KB
/
7-Loops.php
File metadata and controls
87 lines (87 loc) · 2.6 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
//------------------------------------------
// -> While LOOP
//------------------------------------------
$i = 1;
while ($i < 6) {
echo $i. "<br>";
$i++;
}
//------------------------------------------
print "<br>";
$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i. "<br>";
$i++;
}
//------------------------------------------
print "<br>";
$i = 0;
while ($i < 6) {
$i++;
if ($i == 3) continue;
echo $i;
}
//------------------------------------------
// do while Loop
//------------------------------------------
print "<br>";
print "<br>";
$i = 1;
do {
echo $i. "<br>";
$i++;
} while ($i < 6);
//------------------------------------------
// for Loop
//------------------------------------------
print "<br>";
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
//------------------------------------------
// foreach Loop
//------------------------------------------
// Loops through a block of code for each element in an array or each property in an object.
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
//------------------------------------------
$members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($members as $x => $y) {
echo "$x : $y <br>";
}
// Peter : 35
// Ben : 37
// Joe : 43
//------------------------------------------
// Foreach By-reference
//------------------------------------------
// By default, changing an array item will not affect the original array
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") $x = "pink";
}
// var_dump($colors);
print_r($colors);
//------------------------------------------
// By assigning the array items by reference, changes will affect the original array
print("<br>");
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as &$x) {
if ($x == "blue") $x = "pink";
}
var_dump($colors);
?>
</body>
</html>