0

When I apply a negation ! to preg_match, I expect the result of the test to be reversed. Yet this doesn't happen.

<?php

$text = '!SPQR! All roads lead to Rome!';

if (!preg_match('!SPQR!', $text) === 0) {echo 'Result A'."<br />";}
else{echo 'Result B'."<br />";}

if (preg_match('!SPQR!', $text) === 0) {echo 'Result A'."<br />";}
else{echo 'Result B'."<br />";}

Output:

Result B

Result B

Why does negation not reverse the outcome?

Manual says:

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

Manual also says to use === to test.

Use the === operator for testing the return value of this function.

shau
  • 3
  • 3
  • Use `==`, `if ( !preg_match('!SPQR!', $text) == 0)`, not `===`. Or, `if ( preg_match('!SPQR!', $text) !== 0)` – Wiktor Stribiżew Jan 13 '20 at 18:38
  • `!` returns a boolean, you're comparing it to a number. And you're using strict equality, which doesn't do type juggling. – Barmar Jan 13 '20 at 18:38
  • `!x === 0` is not the same as `x !== 0`. – Barmar Jan 13 '20 at 18:39
  • First case: `preg_match` returns `1`, `!1` is `false`, `false` !== `0`. Second case: `preg_match` returns `1`, `1` !== `0`. – Jeto Jan 13 '20 at 18:42
  • I thought that might be the case, but then why does the manual advise using `===` for this test? – shau Jan 13 '20 at 18:42
  • Because `preg_match` can return `false` if an error occurs, and `0` if your pattern didn't match, so it lets you differentiate between them. Use `=== 1` to test if your pattern matched, since it's exactly what it returns then. – Jeto Jan 13 '20 at 18:47

0 Answers0