1

I have a string with values (which are suburbs) like so:

$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";

There COULD be double ups in the suburbs that the string contains. I can't change this fact.

What I am trying to do is create an option list for a drop down menu that a user will use. I do not want to display the same suburb twice( or more for that matter).

What I have so far:

$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
//Explode the suburbs string delimited by a comma
$boom = explode(',', $suburbs);

foreach($boom as $b)
{
$suburbOptionList .= '<option value='.$b.'>'.$b.'</option>';
}
?>
<select> <?php
echo $suburbOptionList;
?>
</select>

I know that this will simply display all of the options but I really don't know how to display each suburb only once. Ive tried a few foreach,and if combinations but they look ugly and work just as bad.

Any help would be appreciated. Cheers in advance!

1
  • Just a side note: I would use a comma with a space , as the delimiter. Since technically you have one Mawson and one ` Mawson`, which are not the same. Commented Jun 10, 2013 at 13:40

1 Answer 1

7

Pass $boom through array_unique() and you'll be fine.

$bada_boom = array_unique($boom);

P.S.: This will not help if you have typos or variations in duplicates. (Elizbeth != Elizabeth). In that case you will need to get creative.

Also, hw (in comments) made a good point about trimming whitespaces. If the suburbs come from an untrusted source and are improperly formatted, you may need to normalize them. This means trimming whitespaces and normalizing capitals:

$boom = array_walk($boom, 'trim');
$boom = array_walk($boom, 'strtolower');
$bada_boom = array_unique($boom);
Sign up to request clarification or add additional context in comments.

1 Comment

In addition to above, you also need to trim values just in case there are spaces around the word, as in your case. You can use $boom = array_walk($boom, 'trim') before calling array_unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.