Search code examples
phpstrcmp

php string compare


I'm trying to compare a specific part of a url to get a list of the endings (which are resource/'location' where location is either state initials or a string). I'm using this to populate a drop down menu. This works well with the 2 letter states, but when I compare the strings it still shows duplicates. This is the code I am working with, and 'National' is the repeated string that does not get filtered out.

$url = explode("/", $row['url']);
if(strcmp(trim($location[$url[2]]),trim($url[2])) != 0)
{
    $location = array($url[2] => $url[2]);
    echo '<option>'.$location[$url[2]].'</option>\n';
}

Is there a better way to compare strings?


Solution

  • Use in_array() (http://php.net/manual/en/function.in-array.php)

    $location = array();
    $url = explode("/", $row['url']);
    if(!in_array($url[2], $location))
    {
        $location[$url[2]] = $url[2];
        echo '<option>'.$location[$url[2]].'</option>\n';
    }