Example 5: Traffic Light System
Conditional structures elseif in PHP
Download file semáforo🎯 Live Demo
Traffic Light Simulator
Change the traffic light color!
Quick change:
Automatic mode:
📖 Code Explanation
Complete PHP Code
<?php
$color = "verde";
if ($color == "verde") {
echo "You can go!";
} elseif ($color == "amarillo") {
echo "Caution!";
} elseif ($color == "rojo") {
echo "Stop! Wait...";
} else {
echo "Invalid color";
}
?>
📝 Line 1: Variable declaration
$color = "verde";
What does it do? Creates a string variable that stores the current traffic light color.
Why is it done this way? Colors are text, so they are assigned in quotes. We use lowercase for consistency.
💡 Concept: String comparison
In PHP, strings are compared with == or ===. It's case-sensitive, that's why we use strtolower() to normalize.
📝 Lines 3-11: if-elseif-else structure
if ($color == "verde") { echo "You can go!";} elseif ($color == "amarillo") { echo "Caution!";} elseif ($color == "rojo") { echo "Stop! Wait...";} else { echo "Invalid color";}
What does it do? Evaluates multiple conditions in sequence until it finds a true one.
Why is it done this way? elseif allows handling multiple specific cases before the default case.
💡 Concept: Flow of elseif
PHP evaluates conditions in order:
1. If the first is TRUE → executes its block
2. If it's FALSE → moves to the next condition
3. If none is TRUE → executes the block else
📝 Differences with switch
With elseif
if ($color == "verde") {
// código verde
} elseif ($color == "amarillo") {
// código amarillo
} else {
// código por defecto
}
With switch
switch ($color) {
case "verde":
// código verde
break;
case "amarillo":
// código amarillo
break;
default:
// código por defecto
}
elseif is better when you need complex conditions. switch is better for simple equality comparisons.
🔄 Multiple Control Structures
if-elseif-else
if ($cond1) {
// código 1
} elseif ($cond2) {
// código 2
} else {
// código 3
}
✅ Advantages:
- Complex conditions
- Custom evaluation
- Total flexibility
switch-case
switch ($variable) {
case "valor1":
// código 1
break;
case "valor2":
// código 2
break;
default:
// código default
}
✅ Advantages:
- More readable
- Better for simple equality checks
- Multiple equal cases
🎯 Common Use Cases
✅ State Systems
Managing states such as: active/inactive/pending
if ($estado == "activo") {
// usuario activo
} elseif ($estado == "inactivo") {
// usuario inactivo
} elseif ($estado == "pendiente") {
// usuario pendiente
}
✅ Access Levels
Permission control: admin/editor/user
if ($nivel == "admin") {
// acceso total
} elseif ($nivel == "editor") {
// acceso edición
} else {
// acceso básico
}
✅ Scoring Systems
Classification by range: A/B/C/D
if ($puntos >= 90) {
$grado = "A";
} elseif ($puntos >= 80) {
$grado = "B";
} elseif ($puntos >= 70) {
$grado = "C";
} else {
$grado = "D";
}
🎯 Key Concepts Learned
Multiple Elseif
- Handles more than two conditions
- Evaluated in sequential order
- Only one block runs
- Useful for categories
String Comparison
- Case-sensitive by default
- Use strtolower()
- == vs === for comparison
- Important for validation
Default Case
- Handles unexpected cases
- Provides robustness
- Improves user experience
- Prevents errors
💪 Practical Exercise
Extend the traffic light system
Practice these changes to improve your skills:
- Add a color "blue" for "proceed with extreme caution"
- Implement a traffic light system for pedestrians (green/red)
- Create a smart traffic light that suggests an action based on the time
- Convert the code to a switch structure and compare
- Add validation for uppercase and lowercase colors
Solution 1: Color blue added
<?php
if ($color == "verde") {
echo "You can go!";
} elseif ($color == "amarillo") {
echo "Caution!";
} elseif ($color == "rojo") {
echo "Stop! Wait...";
} elseif ($color == "azul") {
echo "Proceed with extreme caution";
} else {
echo "Invalid color";
}
?>
Solution 2: Traffic Light pedestrian
<?php
if ($color == "verde") {
echo "🟢 Pedestrian: Cross now";
} elseif ($color == "rojo") {
echo "🔴 Pedestrian: Wait to cross";
} else {
echo "Invalid color for pedestrians";
}
?>
Solution 3: Traffic Light smart
<?php
$hora = date('H');
if ($hora >= 6 && $hora <= 22) {
// Horario normal
if ($color == "verde") {
echo "You can go!";
} elseif ($color == "rojo") {
echo "Stop! Wait...";
}
} else {
// Horario nocturno
if ($color == "verde") {
echo "You can go with caution!";
} elseif ($color == "rojo") {
echo "Stop! Traffic light in night mode";
}
}
?>
Solution 4: With switch
<?php
switch ($color) {
case "verde":
echo "You can go!";
break;
case "amarillo":
echo "Caution!";
break;
case "rojo":
echo "Stop! Wait...";
break;
default:
echo "Invalid color";
}
?>
Solution 5: Validation case-insensitive
<?php
$color = strtolower($color); // Normalize to lowercase
if ($color == "verde") {
echo "You can go!";
} elseif ($color == "amarillo") {
echo "Caution!";
} elseif ($color == "rojo") {
echo "Stop! Wait...";
} else {
echo "Invalid color";
}
?>