0

I have the following array:

$array = [2,2,5,2,2];

I would like to get the number which is different from the others, for example all the numbers are 2 except the number 5. So Is there anyway to get the different number using any array method or better solution? My solution is:

    $array = [2,2,5,2,2];
    $array1 = [4,4,4,6,4,4,4];

    $element = -1;
    $n = -1;
    $count = 0;
    for($i=0; $i<count($array1); $i++) {

        if($element !== $array1[$i] && $element !== -1 & $count==0) {
            $n = $array1[$i];
            $count++;
        }

        $element = $array1[$i];
    }

    dd($n);
1

3 Answers 3

4

You can use array_count_values for group and count same value like:

$array = [2,2,5,2,2];
$countarray = array_count_values($array);
arsort($countarray);
$result = array_keys($countarray)[1]; // 5

Since you only have two numbers, you will always have the number with the least equal values ​​in second position

Reference:


A small clarification, for safety it is better to use arsort to set the value in second position because if the smallest number is in first position it will appear as the first value in the array

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

Comments

0

You can user array_count_values which returns array with item frequency.

Then use array_filter to filter out data as follow:

 $arrayData = [2,2,2,5];
 $filterData = array_filter(array_count_values($arrayData), function ($value) {
                     return $value == 1;
               });
print_r($filterData);

Inside array_filter(), return $value == 1 means only get the data with 1 frequency and thus filter out the other data.

1 Comment

This good work too, the "only problem" is if the smallest count is plus 1
0
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
print $number . ' | ' . ($count > 1 ? 'Duplicate value ' : 'Unique value ') . "\n";
 }
}

$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
UniqueAndDuplicat($array1);
//output: 2 | duplicate value  5 | Unique value
UniqueAndDuplicat($array2);
//output: 4 | duplicate value  5 | Unique value
?>

Use this function to reuse this you just call this function and pass an Array to this function it will give both unique and duplicate numbers.

If you want to return only Unique number then use the below code:

<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
if($count == 1){
return $number;
    }
 }
}

$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
echo UniqueAndDuplicat($array1); // 5
echo "<br>";
echo UniqueAndDuplicat($array2); // 6
?>

Comments

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.