Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda