$a == $b or preg_match(“/^$a/”, $b) – what to choose and why?

Option 1:

if (
$a == $b &&
$a == $c &&
$a == $e
)

Option 2:

if (
preg_match("/^$a/", $b) &&
preg_match("/^$a/", $c) &&
preg_match("/^$a/", $e)
)

Which option to choose and why?

P.S. I assume that the first option is faster, but still, I want to hear the opinions of users who really know.


Answer 1

preg_match is hardly faster than regular comparison, since it needs to load the regulator parser at least. And the comparison will call itself strcmpand that’s it.
But here’s what happens if $a contains a regular expression…


Answer 2

The first option checks for equality, while the second one checks for an occurrence.
1) 1 = 1fghfgh : true
2) 1sdfsdf3 = 1 : false because not included in substring

$a = "1ertert";
$b = 1;
if ($a == $b )
    echo "true<br/>";
else
    echo "false<br/>";
if (preg_match("/^$a/", $b))
    echo "true<br/>";
else
    echo "false<br/>";

Answer 3

I would suggest this:

if ( $a === $b === $c === $e )

===is a strict comparison, no typecasting