2

I want to first get the keys with the same values and then keep the keys with the longest string. Here is the code compiled so far:

<?php
$data = array('Anna' => 1, 'Ann' => 1, 'Tommy' => 100, 'Tom' => 100);
$total = array_count_values($data);
$filtered = array_filter($data, function ($value) use ($total) {
return $total[$value] > 1;
});

print_r($filtered);
?>

The current output:

Array ( [Anna] => 1 [Ann] => 1 [Tommy] => 100 [Tom] => 100 )

My expected output:

Array ( [Anna] => 1 [Tommy] => 100)

Many thanks for help.

0

2 Answers 2

4

Not necessarily the most optimized solution, but you could write it up using simple check:

$data = array('Anna' => 1, 'Ann' => 1, 'Tommy' => 100, 'Tom' => 100, 'Dan' => 200, 'Danny' => 200);
$total = array_count_values($data);

$filtered = array_filter($data, function ($value) use ($total) {
    return $total[$value] > 1;
});

foreach($data as $key => $value) {
    $foundKey = array_search($value,$filtered);
    if($foundKey){
        if(strlen($foundKey) < strlen($key)){
            unset($filtered[$foundKey]);
        } elseif(strlen($foundKey) > strlen($key)) {
            unset($filtered[$key]);
        }
    }
}
print_r($filtered);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your solution!
1

Not sure to post it after even answer is accepted but I have simple hack for this using ksort() and array_flip():

$data = array('Anna' => 1, 'Ann' => 1, 'Tommy' => 100, 'Tom' => 100, 'Dan' => 200, 'Danny' => 200);
ksort($data);
$result=array_flip(array_flip($data));
print_r($result);

ksort(): Sort an array by key

array_flip(): Flip all keys with their associated values in an array

Demo

1 Comment

Perfect! Thank you very much for your help.

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.