Example 6: Day of the Week

switch-case structure for multiple options

Download file dia_semana

🎯 Live Demo

Weekly Calendar

1
Mon
2
Tue
3
Wed
4
Thu
5
Fri
6
Sat
7
Sun
Day 6
Saturday
🎉

Select a day!

1 = Monday, 7 = Sunday

Quick days:

💡 Day facts:

😴 Saturday: The only day that keeps its Hebrew origin (Sabbath). A day of rest in many cultures.

📖 Code Explanation

Complete PHP Code

<?php
$dia = 6;

switch ($dia) {
    case 1:
        echo t('Lunes');
        break;
    case 2:
        echo t('Martes');
        break;
    case 3:
        echo t('Miércoles');
        break;
    case 4:
        echo t('Jueves');
        break;
    case 5:
        echo t('Viernes');
        break;
    case 6:
        echo t('Sábado');
        break;
    case 7:
        echo t('Domingo');
        break;
    default:
        echo t('No es un día de la semana');
}
?>

📝 Line 1: Control variable

$dia = 6;

What does it do? Defines the variable that will control the flow of the switch.

Why is it done this way? Switch needs a variable to compare against the different cases.

💡 Concept: Control variable

En estructuras switch, una sola variable se evalúa múltiples veces contra diferentes valores posibles.

📝 Lines 3-25: switch structure

switch ($dia) {
case 1:
echo t('Lunes');
break;
// ... more cases ...
default:
echo t('No es un día de la semana');
}

What does it do? Evaluates the variable $dia against each case and runs the code for the matching case.

Why is it done this way? Switch is ideal when we have a variable that can take several specific values.

💡 Concept: break

break es crucial en switch. Sin él, PHP ejecutaría todos los casos siguientes (fall-through).

📝 Case default

default:
echo t('No es un día de la semana');

What does it do? Runs when no case matches the variable.

Why is it done this way? Handles unexpected values and makes the code more robust.

💡 Concept: Defensive Programming

Siempre incluye un caso default para manejar valores inesperados y prevenir errores.

🔍 Anatomy of the Structure Switch

1. Expression switch

switch ($variable)

The variable that will be evaluated against each case.

2. Cases (cases)

case valor:

Each possible value the variable can have.

3. Code block

// code to execute

The statements that run if there is a match.

4. Break

break;

Ends the execution of the switch.

5. Default

default:

Runs if no case matches.

⚖️ Switch vs If-Else: When to use each one?

✅ Use SWITCH when:

  • You compare a variable against specific values
  • You have many cases (more than 3-4)
  • The conditions are simple equality checks
  • The code is more readable with switch
switch ($dia) {
    case 1: echo t('Lunes'); break;
    case 2: echo t('Martes'); break;
    // ...
}

✅ Use IF-ELSE when:

  • The conditions are complex
  • You use operators like >, <, >=
  • You have few cases (2-3)
  • You need to evaluate multiple variables
if ($edad >= 18) {
    echo "Older";
} else {
    echo "Younger";
}

🚀 Advanced Use Cases for Switch

Multiple cases, same code

Several cases can run the same code.

switch ($dia) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        echo "Working day";
        break;
    case 6:
    case 7:
        echo "Weekend";
        break;
}

Switch with strings

It also works with text strings.

switch ($color) {
    case "red":
        echo "Stop";
        break;
    case "green":
        echo "Go";
        break;
}

Return in switch

You can use return in functions.

function getDia($numero) {
    switch ($numero) {
        case 1: return t('Lunes');
        case 2: return t('Martes');
        default: return t('Inválido');
    }
}

🎯 Key Concepts Learned

structure Switch

  • Ideal for multiple options
  • More readable than many if-else
  • Only compares by equality
  • Requires break for each case

Control Flow

  • Break ends execution
  • Without break: fall-through
  • Default handles unexpected cases
  • Order of cases can matter

Best Practices

  • Always include a default
  • Use break in each case
  • Keep cases simple
  • Document complex cases

💪 Practical Exercise

Extend the days system

Practice these changes to improve your skills:

  1. switch Convert the if-elseif-else and compare readability
  2. Add day information in English alongside Spanish
  3. Create a system that detects whether the day is a workday, weekend or holiday
  4. Implement a switch that works with day names instead of numbers
  5. Create a function that receives the day number and returns an array with full information

Solution 1: With if-elseif

<?php
if ($dia == 1) {
    echo t('Lunes');
} elseif ($dia == 2) {
    echo t('Martes');
} elseif ($dia == 3) {
    echo t('Miércoles');
} elseif ($dia == 4) {
    echo t('Jueves');
} elseif ($dia == 5) {
    echo t('Viernes');
} elseif ($dia == 6) {
    echo t('Sábado');
} elseif ($dia == 7) {
    echo t('Domingo');
} else {
    echo t('No es un día de la semana');
}
?>

Solution 2: Bilingual

<?php
switch ($dia) {
    case 1:
        echo "Lunes / Monday";
        break;
    case 2:
        echo "Martes / Tuesday";
        break;
    // ... otros días ...
}
?>

Solution 3: Day type

<?php
switch ($dia) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        echo "Día laboral";
        break;
    case 6:
    case 7:
        echo "Fin de semana";
        break;
    default:
        echo "Día inválido";
}
?>

Solution 4: With strings

<?php
$nombreDia = "lunes"; // en minúsculas

switch ($nombreDia) {
    case "lunes":
        echo "Día 1";
        break;
    case "martes":
        echo "Día 2";
        break;
    // ... otros días ...
    default:
        echo "Día no válido";
}
?>

Solution 5: Function with array

<?php
function getDiaInfo($numero) {
    switch ($numero) {
        case 1:
            return ["nombre" => t('Lunes'), "ingles" => "Monday", "tipo" => "laboral"];
        case 2:
            return ["nombre" => t('Martes'), "ingles" => "Tuesday", "tipo" => "laboral"];
        case 6:
            return ["nombre" => t('Sábado'), "ingles" => "Saturday", "tipo" => "fin_semana"];
        case 7:
            return ["nombre" => t('Domingo'), "ingles" => "Sunday", "tipo" => "fin_semana"];
        default:
            return ["nombre" => "Inválido", "ingles" => "Invalid", "tipo" => "invalido"];
    }
}

$info = getDiaInfo(1);
echo $info['nombre']; // Lunes
?>