phpphp-7php-5.5

PHP5 to PHP7 if test difference in switch case


I have recently upgraded from PHP5 to PHP7. This gave me an error. After distilling the problem I was able to fix. However I still found it a weird problem.

Given the following code:

<?php

$r = "R";
$a = false;

switch ($r) {
  case "R":
  default:
    // Test 1
    if($a){
      echo("error;");
    }else{
      echo("working;");
    }
    // Test 2
    if($a !== false){
      echo("error;");
    }else{
      echo("working;");
    }
    break;
}
?>

The output of this code is: PHP 5.5.9:

working;working;

PHP 7.0.13:

error;working;

Why is this difference there?

However when removing the switch case block around 'Test 1', this result in working.

Changing the initial declaration of $r to something else then 'R' also results in working;working;. This means that depending on if we start from 'case' or from 'default' the result is different.

When adding the line var_dump($a); in front of the 'Test 1' (inside the switch case) it results in bool(false) working;working;

Odd observation: When running the code for the first time it sometimes result in: working;working; and by pressing F5 it results in error;working; again.

Why does it react differently in this way?

My best guess it that this has something to do with type conversion.


Solution

  • I never solved this problem. But after regular updates on the server it got solved at some point.

    It probably was a problem in php somewhere as I did not update the page, but it is solved now.

    ( running PHP 7.2.24 now ) So just update your php version if you have this problem.