Strcmp vs equal ==

In which cases should I consider strcmp rather than just == ?
for example to compare if two IPs or two domains are the same better to use == or strcmp?

strcmp only returns a benefit if you need to know which one is different. Quick and dirty explanation is it sorts them, then returns a comparison of them

So if you have

$var1 = 'abc';
$var2 = 'def';
$var3 = 'ghi';
$var2a = 'def';

echo strcmp($var2, $var1); // returns 2  (first string is "greater" than second string)
echo strcmp($var2, $var3); // returns 1  (first string is "less" than second string)
echo strcmp($var2, $var2a); // returns 0 (both values are equal)

Now if you don’t care how they compare, rather just checking that they match, then use === (not ==). It’s a “type safe” comparison. In other words.

$var1 = 1234;
$var2 = '1234';
$var3 = '1234';
$var4 = 1234;

echo ($var1 == $var2); // will return true because $var1 and $var2 are changed to the same data type before comparing.
echo ($var1 === $var2); // will return false because a numeric and a string can't be equal.
echo ($var3 === $var2); // will return true because the strings have the same value.
echo ($var1 === $var4); // will return true because the numeric variables have the same value.
1 Like

It’s just a binary safe comparison, I always prefer ‘===’ over strcmp. Ideally used whenever your dealing with secruity.

strcmp()’s main use case is sorting as the (user defined) sort functions must return an integer.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.