1

This is one of those situations where I'm sure that there's a simple solution, and I need help getting to it.

Suppose we're dealing with three phone numbers: home (h), office (o) and mobile (m). We need to avoid displaying duplicate phone numbers to the end user.

To better explain, here are three sample cases (in PHP):

Case 1:

$phone = array(
    'h' => '212-555-1212',
    'o' => '212-555-1212',
    'm' => '212-555-1212'
);

Should yield:

212-555-1212 (h,o,m)

Case 2:

$phone = array(
    'h' => '212-555-1212',
    'o' => '212-555-1234', // different
    'm' => '212-555-1212'
);

Should yield:

212-555-1212 (h,m)
212-555-1234 (o)

Case 3:

$phone = array(
    'h' => null,
    'o' => '212-555-1234',
    'm' => '212-555-1212'
);

Should yield:

212-555-1234 (o)
212-555-1212 (m)

I have tried using various case statements, by checking for each scenario, but it's complicated by the fact that some values might be empty. I have also tried using overly-complicated if/elseif/else conditions, but again, it's extremly inelegant.

My best efforts resulted from using array_filter to remove empty elements from the array and the using array_unique to remove duplicates, but then I lose the H/O/M key:

$phone = array_filter(array_unique($phone));

How should I approach this?

0

1 Answer 1

3

I would first flip the array. Create a new array with the phone number as the key. Something like this:

$numbers = [];
foreach($phone AS $type => $number) { 
    $numbers[$number][] = $type;
}

Now you have a $numbers array, with unique phones, and an array of types for each one.

To display your output then:

foreach($numbers AS $number => $types) {
    echo $number . " (" . implode(",",$types) . ")";
}

I've wrapped this up as a real quick function, and run all three of your cases through. You can see the code and output here:

https://3v4l.org/U6c4K

Sign up to request clarification or add additional context in comments.

1 Comment

Creative thinking! Thank you, I'll keep this one in my toolbox.

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.