Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
Can any one explain Switch Case behaviour?

on all version of php, i have an problem with switch case statement I can't understand this behaviour =>

        $coef = 0;

    switch($coef) {
        case ($coef >= 0 && $coef <= 2.1):
            var_dump( 1);
            break;
        case ($coef > 2.1 && $coef <= 4.1):
            var_dump( 2);
            break;
        case ($coef > 4.1 && $coef <= 6.1):
            var_dump( 3);
            break;
        case ($coef > 6.1 && $coef <= 8.1):
            var_dump( 4);
            break;
    }

// Return 2 not 1

So the first condition (coef >= 0 && $coef <= 2.1) => return true; The second return false: ($coef > 2.1 && $coef <= 4.1) => return false; The second case always return the result.

To have a normal behaviour we need to write switch case like that :

    switch($coef) {
        case ($coef === 0):
        case ($coef > 0 && $coef <= 2.1):
            var_dump( 1);
            break;
        case ($coef > 2.1 && $coef <= 4.1):
            var_dump( 2);
            break;
        case ($coef > 4.1 && $coef <= 6.1):
            var_dump( 3);
            break;
        case ($coef > 6.1 && $coef <= 8.1):
            var_dump( 4);
            break;
    }
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

As explained in PHP- Switch case statement with conditional switch, switch always compares the top expression with the result of whatever expression you put into the case.

As explained in the link (and by lukas.j), you need to put true in your top statement, if you want to stop at the first line which evaluates to true.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda