Search code examples
phpregexstrcmp

PHP strcmp() is giving me number '6' as output


I am comparing two short strings (some containing numbers, some containing letters, some are mixed) with strcmp() expecting output would be 0, -1 or 1 (or I will say it differently: there definitely has to be 1 match but it is always 'no match', that is always not 0) but for some strange reason I am getting '6' no matter what, this is my code:

$_delim = '</div>';
$_str = '';
$_struct = explode($_delim, file_get_contents($_pthPHP.'_sets.php'));
$_c = count($_struct);
$_patternIMG = '/data-img="(.*?)"/';
$_patternLIKTYPE = '/data-link-type="(.*?)"/';

for ($i = 0; $i < ($_c - 1); $i++)
{
    preg_match($_patternIMG, $_struct[$i], $matchesA); // DATA-IMG = NAZOV SETU
    $_iteratedSet = explode('<?= $def_path ?>', $matchesA[1]);
    $_actualSet = explode('-', $verzia);

    $_strA = trim($_iteratedSet[1]);
    $_strB = trim($_actualSet[0]);

    echo strcmp((string)$_strA, (string)$_strB).'<br />'; // TESTING COMPARISON VALUE

    if(strcmp($_strA, $_strB) == 0)
    {
        preg_match($_patternLIKTYPE, $_struct[$i], $matchesB); // DATA-LINK-TYPE
        $_linkType = $matchesB[1];
        echo 'link type = '.$_linkType;
        break;
    }
}

I was looking for a solution and I found here on StackOverflow one supposed solution which basically adds file prefix of '(string)' to both compared strings but it has no effect whatsoever and the output is still that strange '6' - anyone know why and can help me, please?

SOLVED

2 things happened: - I mistakenly thought output can be only 0, 1 or -1 - I mistakenly entered wrong variable to one of the strings :-(

...so now all is as expected, thanx to @Erhan for the explanation (the code above is already fixed so it actually show the functional one)


Solution

  • Your output does not exactly has to be 1 or -1. If they are equal output will be zero (0) if not output will be <0 or >0 from php.net

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