George Vladimir
George Vladimir

Reputation: 123

Find two values that are equal in array

 $arr = array(
     1, 1, 2, 3, 4
 );

How to find out the pair from this array ?
Keep in mind that the pair from array could be any number (1,2,4,3,2) or (3,3,1,2,4); I just give an random example above.

if there is a pair in array
   echo "The pair number is 1";

Upvotes: 2

Views: 779

Answers (6)

mickmackusa
mickmackusa

Reputation: 47874

All of my methods will return the desired result as long as there IS a duplicate. It is also assumed because of your sample input, that there is only 1 duplicate in the array. The difference between my methods (and the other answers on this page) will be milliseconds at most for your input size. Because your users will not be able to distinguish between any of the correct methods on this page, I will suggest that the method that you implement should be determined by "readability","simplicity", and/or "brevity". There are many coders who always default to for/foreach/while loops. There are others who always defer to functional iterators. Your choice will probably just come to down to "your coding style".

Input:

$arr=[1,1,2,3,4];

Method #1: array_count_values(), arsort(), key()

$result=array_count_values($arr);
arsort($result);                 // this doesn't return an array, so cannot be nested
echo key($result);
// if no duplicate, this will return the first value from the input array

Explanation: generate new array of value occurrences, sort new array by occurrences from highest to lowest, return the key.


Method #2: array_count_values(), array_filter(), key()

echo key(array_filter(array_count_values($arr),function($v){return $v!=1;}));
// if no duplicate, this will return null

Explanation: generate the array of value occurrences, filter out the 1's, return the lone key.


Method #3: array_unique(), array_diff_key(), current()

echo current(array_diff_key($arr,array_unique($arr)));
// if no duplicate, this will return false

Explanation: remove duplicates and preserve the keys, find element that went missing, return the lone value.

Further consideration after reading: https://www.exakat.io/avoid-array_unique/ and the accepted answer from array_unique vs array_flip I have a new favorite 2-function one-liner...

Method #4: array_count_values(), array_flip()

echo array_flip(array_count_values($arr))[2];
  // if no duplicate, this will show a notice because it is trying to access a non-existent element
  // you can use a suppressor '@' like this:
  // echo @array_flip(array_count_values($arr))[2];
  // this will return null on no duplicate

Explanation: count the occurrences (which makes keys of the values), swap the keys and values (creating a 2-element array), access the 2 key without a function call. Quick-smart!

If you wanted to implement Method #4, you can write something like this:(demo)

$dupe=@array_flip(array_count_values($arr))[2];
if($dupe!==null){
    echo "The pair number is $dupe";
}else{
    echo "There were no pairs";
}

There will be many ways to achieve your desired result as you can see from all of the answers, but I'll stop here.

Upvotes: 3

Mehul Akabari
Mehul Akabari

Reputation: 101

$arr = array(
     1, 1, 2, 3, 4
 );
 echo "<pre>";          
$vals = array_count_values($arr);
foreach ($vals as $key => $value) {
    if($value%2==0){
        echo "The pair number is ".$key."<br>"; 
    }else{
        echo "The not pair number is ".$key."<br>"; 
    }

}

Upvotes: 0

Just a student
Just a student

Reputation: 11030

First sort the array, then check if there are two numbers on consecutive indexes with the same value.

This is the most efficient solution: sorting is done in O(n log n) time1 and doing the checking takes O(n) time. Overall, you'll have the answer in O(n log n) time. Naive approaches will use O(n2) time.

If you don't want to modify the original array, do all of the above on a copy.

function hasEqualPair($arr) {
    sort($arr);
    $l = count($arr);
    for ($i = 1; $i < $l; ++$i) {
        if ($arr[$i] === $arr[$i - 1]) {
            return true;
        }
    }
    return false;
}

var_dump(hasEqualPair(array(1, 2, 4, 3, 2))); // true
var_dump(hasEqualPair(array(1, 1, 2, 3, 4))); // true
var_dump(hasEqualPair(array(3, 3, 1, 2, 4))); // true
var_dump(hasEqualPair(array(3, 5, 1, 2, 4))); // false

Try it online!

Of course, if you want to know what the pair is, just change return true in the above function to return $arr[$i]. You then might want to change the function name to getEqualPair as well.

1 The sort function in PHP uses Quicksort. It is possible to make that always run in O(n log n) time, but the implementation in PHP probably has an average running time of O(n log n), with worst case running time still O(n2).

Upvotes: 0

Blueline
Blueline

Reputation: 408

You can first count all the values in the array, then for each distinct value check if it occurs twice in the array.

<?php 
$array = array(1, 1, 2, 3, 4);
$vars = array_count_values($array);

foreach($vars as $key => $var) {
    if($var == 2) {
        echo "The pair number is " . $key . "<br>";
    }
}
?>

Upvotes: 1

u_mulder
u_mulder

Reputation: 54831

Use built-in array_count_values. Then iterate over results and check if count is greater than 1.

$arr = array(
    1, 1, 2, 3, 4
);
$values = array_count_values($arr);
foreach ($values as $key => $value) {
    if ($value > 1) {
        echo 'Pair: ' . $key;
        // break, if you need to show first pair only
        // break;
    }
}

Upvotes: 1

Mohammad Hamedani
Mohammad Hamedani

Reputation: 3354

First sort your array, then use foreach loop and if current and next are equal and not echo this item before this time, echo item is pair.

$arr = array(
     1, 3, 1, 2, 2, 2, 3, 4
 );

sort($arr);

$last_number = null;
foreach($arr as $key => $item) {
    if(array_key_exists($key + 1, $arr)) {
        if($item === $arr[$key + 1]) {
            if($last_number !== $item) {//prevent duplicate echo pair of one item
                echo 'The pair number is ' . $item;
                $last_number = $item;
            }
        }
    }
}

Upvotes: 1

Related Questions