Search code examples
phpstrcmp

Difference between "==" and "strcmp" in PHP


I was asked to create simulation array_keys function, but check equality "==" returns false. But with "strcmp ($a, $b) == 0" return true.

class Utility
{
    public function convertArrayKeys(array $array)
    {
        $i = 0;
        $elements = [];
        foreach ($array as $element=>$value) {
            $elements[] = '  ' . $i++ . " => '" . $element . "'";
        }

        return 'array ( ' . implode(', ', $elements) . ', )';
    }

    public function testStrings(array $array)
    {
        $arrayOur = $this->convertArrayKeys($array);
        $arrayPhp = var_export(array_keys($array),true);
        if ($arrayOur == $arrayPhp){
            echo 'They are identical :)';
        } else {
            echo 'They are not identical :(';
            echo '<br>';
            print_r(str_split($arrayOur));
            echo '<br>';
            print_r(str_split($arrayPhp));
        }
    }
}

View:

$repository = array('box'=>'blue', 'cube'=>'red', 'ball'=>'green');
$utility = new Utility();

echo "OUr array_keys: ";
echo $utility->convertArrayKeys($repository);
echo "<br />";
echo "PHP array_keys: ";
print_r (var_export(array_keys($repository)));

echo "<hr >";
echo "<br />";

echo $utility->testStrings($repository);

I would appreciate to know because


Solution

  • Edit: The reason that the two don't work in THIS instance is that your functions dont produce identical outputs: yours produces:

    array ( 0 => 'box', 1 => 'cube', 2 => 'ball', )

    where the php function produces:

    array ( 0 => 'box', 1 => 'cube', 2 => 'ball', )

    If you were to view that in the web browser i think the web browser renderer does whitespace trickery. However try putting uhh <pre> tags around it (or run in command line to check).


    Basically == does more then compare the two values - the documentation suggests "after type juggling". You can get some weird things by comparing strings using ==. One good example is: '1e3' == '1000'. It is useful to use ==at times, but possibly not in conjunction with strings.

    Strcmp also though doesn't return a true/false answer, but a -1, 0, 1 answer indicating which string is alphabetically in front of the other.

    You should also look at === which can also have helpful uses, but personally I would stick with strcmp with strings.