DisplayName
DisplayName

Reputation: 51

Echo only the duplicate values of array_count_values result php

After both myself and a friend searching for hours upon end, and trying numerous things we are unable to find out how to echo only the duplicate values of array_count_values result. I will break it down:

We have numerous select boxes, which build the array when sent via GET, for example:

    <div class="form-group col-sm-2 mb-sm">
            <select name="select[]" class="form-control">
                <option value="" disabled="" selected="">Select</option>
                <option value="optionOne">Option 1</option>
                <option value="optionTwo">Option 2</option>
            </select>
        </div>
        <div class="form-group col-sm-2 mb-sm">
            <select name="select[]" class="form-control">
                <option value="" disabled="" selected="">Select</option>
                <option value="optionOne">Option 1</option>
                <option value="optionTwo">Option 2</option>
            </select>
        </div>
        <div class="form-group col-sm-2 mb-sm">
            <select name="select[]" class="form-control">
                <option value="" disabled="" selected="">Select</option>
                <option value="optionOne">Option 1</option>
                <option value="optionTwo">Option 2</option>
            </select>
        </div>

We are then doing the following:

if (max(array_count_values($_GET['select'])) == 2) {
   $twoSelected = '2 of the selections are the same, which were (DUPLICATE SELECTION HERE)';
}

We have tried a foreach loop, but can't seem to get it to work.

Any help will be very much appreciated.

Kind Regards

Upvotes: 0

Views: 654

Answers (2)

MisterX
MisterX

Reputation: 310

Try this one

$array = array("test", "hello", "test", "world", "hello");

$duplicatedValuesArray = array_keys(array_filter(array_count_values($array), function($v) {
    return $v > 1;
}));

echo implode(', ',$duplicatedValuesArray);

Upvotes: 2

Avinash Kumar Singh
Avinash Kumar Singh

Reputation: 117

I think below code is helpful for you to get duplicate value.

$array = array(1=>'12334',2=>'123345',3 =>'Helloo' ,4=>'hello', 5=>'helloo');

// Convert every array value to uppercase, and remove all duplicate values
$notdublicates = array_unique(array_map("strtoupper", $array));

// The difference in the original array $array, and the $notdublicates array
// will be the duplicate values
$getduplicates = array_diff($array, $notdublicates);
print_r($getduplicates);

Upvotes: 0

Related Questions