Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!