Why does the condition not work? In fact, it turns out - if 403! = 403 then we assign true. Obviously, the condition does not work here, but it, all the same, assigns true. What I do not understand?

$headers = 'HTTP/1.1 403 Forbidden'; preg_match('/[0-9]{3}/ui', $headers, $matches); if((int)$matches[0] != 403) { $headers_check = true; } echo $headers_check; //Результат вывода 1 
  • one
    Where do you have $headers_check declared? sandbox.onlinephpfunctions.com/code/… - Suvitruf
  • , Forgot that it is necessary to initialize variables! Thanks for the tip! The issue is resolved! - unreal_serg

3 answers 3

Everything works correctly for you, add else $headers_check = false and output the variable through var_dump and you will see the correct processing of the condition.

 $headers = 'HTTP/1.1 403 Forbidden'; preg_match('/[0-9]{3}/ui', $headers, $matches); if((int)$matches[0] != 403) { $headers_check = true; } else { $headers_check = false; } var_dump($headers_check); 
  • Exactly, thanks! - unreal_serg

Because variables need to be defined completely.

 $headers = 'HTTP/1.1 403 Forbidden'; preg_match('/[0-9]{3}/ui', $headers, $matches); if((int)$matches[0] != 403) { $headers_check = true; } else $headers_check = false; var_dump($headers_check); 

Especially if you reuse them in code.

And even better so

 $headers = 'HTTP/1.1 403 Forbidden'; preg_match('/[0-9]{3}/ui', $headers, $matches); $headers_check = ((int)$matches[0] != 403); var_dump($headers_check); 
  • Such $ headers_check = ((int) $ matches [0]! = 403); I haven't tried using it yet, thanks! - unreal_serg
  • @unreal_serg Mark one of the following answers as correct - Anton Shchyrov

Before the condition, initialize the variable.

 $headers_check = false;