forked from bradtraversy/php-crash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
05_loops.php
86 lines (63 loc) · 1.33 KB
/
05_loops.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
<?php
/* -------- Loops & Iteration ------- */
/* ------------ For Loop ------------ */
/*
** For Loop Syntax
for (initialize; condition; increment) {
// code to be executed
}
*/
for ($x = 0; $x <= 10; $x++) {
echo "Number: $x <br>";
}
/* ------------ While Loop ------------ */
/*
** While Loop Syntax
while (condition) {
// code to be executed
}
*/
$x = 1;
while ($x <= 5) {
echo "Number: $x <br>";
$x++;
}
/* ---------- Do While Loop --------- */
/*
** Do While Loop Syntax
do {
// code to be executed
} while (condition);
do...while loop will always execute the block of code once, even if the condition is false.
*/
do {
echo "Number: $x <br>";
$x++;
} while ($x <= 5);
/* ---------- Foreach Loop ---------- */
/*
** Foreach Loop Syntax
foreach ($array as $value) {
// code to be executed
}
*/
// Loop through an array
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $x) {
echo "Number: $x <br>";
}
// Use the indexes within the loop
$posts = ['Post One', 'Post Two', 'Post Three'];
foreach ($posts as $index => $post) {
echo "${index} - ${post} <br>";
}
// Use the keys within the loop for an associative array
$person = [
'first_name' => 'Brad',
'last_name' => 'Traversy',
'email' => '[email protected]',
];
// Get Keys
foreach ($person as $key => $val) {
echo "${key} - ${val} <br>";
}