ONE NET WIKI Free and professional IT Wiki

String comparison using === vs. strcmp in PHP

2018-10-29 ONE NET WIKI


There are some operators in PHP to compare strings: "==", "===" and strcmp(). Many people may be confused about their difference.

== (loose comparison)

Never use == in PHP to compare string. It will not do what you expect.

1) Comparing any string to 0 with == will return true, Obviously, this is false.

2) Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical.

// return true
echo (1 == '1') ? 'true' : 'false';
echo (1 == true) ? 'true' : 'false';
echo '1e3' == '1000';

=== (strict comparison)

Instead, you should use === to compare strings.

=== will give you the best performance and is much faster than strcmp() although they are both case sensitive.


int strcmp (string $str1, string $str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

You should use strcmp() if you wish to order/compare strings lexicographically.

If you just wish to check for equality, === is is the best.

Editor's Note: All the articles in this website are original. If reproduced, please indicate the source and link.
All Comments (0)
Expand to publish a comment

Web Development

Web Management

Web Marketing

Web Security