Search code examples
phpstrcmp

PHP String Compare not working as expected


I have an array and some of the values have the text value "unknown".

If I use strcmp, I'm not getting the results as expected.

For example:

echo $array[8];

outputs the word "unknown".

strcmp($array[8],"unknown");

outputs -104.

strcmp(trim($array[8]),"unknown");

Outputs -57.

I don't understand why these strings are not equal. I'm just trying to get a 0 value so I can filter out the array values with "unknown" with a loop.


Solution

  • If you want to check if string is equal, use ===

    if(trim($array[8]) === "unknown"){ ..
    

    You can even write your own callback for the filter method:

    $array_filtered = array_filter($array, function($value){
        return trim($value) !== "unknown";
    });