CITW 185 Web Development PHP & MySQL
1. What Are Decisions and Loops?
- Decisions (Conditionals): Used to execute specific blocks of code based on certain
conditions.
Common constructs include
if
, else
, elseif
, switch
, etc.
- Loops: Allow repeated execution of a block of code while a condition holds true. Common
loops
in PHP include
for
, while
, do-while
, and foreach
.
2. Why Are Decisions and Loops Important?
- Automation: They allow repetitive tasks to be automated, saving time and reducing errors.
- Conditional Logic: Decisions enable dynamic behavior in applications based on user input or
data.
- Efficiency: Loops can process large datasets or perform iterative tasks without repetitive
coding.
3. Key Features
- Decisions:
if
checks a condition and executes a block of code if true.
else
specifies what to do when the condition is false.
elseif
provides multiple conditions to check.
switch
handles multiple possible values of a single variable.
- Loops:
for
loops are ideal when the number of iterations is known.
while
loops execute as long as a condition remains true.
do-while
loops guarantee at least one execution of the block before checking the
condition.
foreach
is used specifically for iterating over arrays.
4. Best Practices
- Use meaningful condition names to make your code more readable.
- Avoid infinite loops by ensuring conditions will eventually become false.
- Use
break
to exit loops early if a condition is met.
- Combine conditions efficiently using logical operators (
&&
, ||
) for clarity and
performance.
Assignments
-
Decision Examples
-
Loops
-
Your creative assignment is to demonstrate your command of decisions and loops. I suggest you use a
form to gather values and then preform a series of decisions and loops to present something
of value.