-
Notifications
You must be signed in to change notification settings - Fork 1k
/
04.php
98 lines (56 loc) · 1.76 KB
/
04.php
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
88
89
90
91
92
93
94
95
96
97
98
<?php // LOOPS
echo '<p>CLASSICAL LOOP</p>'; // CLASSICAL LOOP
for ($i = 0; $i < 10; $i++) {
echo 'i:' . $i . ' ';
}
echo '<p>CLASSICAL LOOP WITH ARRAYS</p>'; // CLASSICAL LOOP WITH ARRAYS
$numbers = [-3.2, 5.3, 3, 1];
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . ' ';
}
echo '<p>REVERSE LOOP</p>'; // REVERSE LOOP
for ($i = 5; $i >= 0; $i--) {
echo 'i:' . $i . ' ';
}
echo '<p>NESTED LOOP</p>'; // NESTED LOOP
for ($i = 0; $i < 3; $i++) {
echo 'i:' . $i . ' ';
for ($j = 2; $j > 0; $j--) {
echo 'j:' . $j . ' ';
for ($k = 0; $k < 2; $k++) {
echo 'k:' . $k . ' ';
}
}
}
echo '<p>ITERATOR LOOP</p>'; // ITERATOR LOOP
$colors = ['red', 'green', 'blue', 'yellow'];
foreach ($colors as $color) {
echo $color . ' ';
}
echo '<p>WHILE LOOP</p>'; // WHILE LOOP
$i = 0;
while ($i <= 3) {
$i++;
echo 'Hello ' . $i . ' ';
}
echo '<p>DO-WHILE LOOP</p>'; // DO-WHILE LOOP
$i = 0;
do {
$i++;
echo 'Bye ' . $i . ' ';
} while($i <= 3);
echo '<p>EXAMPLE 1 (SUMMATION): sum up all the elements of an array</p>'; // EXAMPLE 1
$my_array = [-4.3, 2, -0.7, 1.5, 3.5];
$sum = 0;
for ($i = 0; $i < count($my_array); $i++) {
$sum = $sum + $my_array[$i];
}
echo '<p>The sum of all the elements of the array is ' . $sum . '</p>';
echo '<p>EXAMPLE 2 (PRODUCT): multiply all the elements of an array</p>'; // EXAMPLE 2
$my_array = [3, 2, -1, 1, 4];
$prod = 1;
for ($i = 0; $i < count($my_array); $i++) {
$prod = $prod * $my_array[$i];
}
echo '<p>The multiplication of all the elements of the array is ' . $prod . '</p>';
?>