DatabaseDiver
DatabaseDiver

Reputation: 73

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?

Upvotes: 1

Views: 918

Answers (2)

Nick
Nick

Reputation: 6346

why are you even using strcmp? Also, why are you resetting $location?

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

Not sure what would cause the duplicates though, think I'd need to have an example to play with to figure that out.

EDIT: Ignore the above, after reading the other answer I see what you're trying to achieve. The question wasn't very clear on that.

Upvotes: 0

Richard
Richard

Reputation: 4415

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';
}

Upvotes: 2

Related Questions