David Concha
David Concha

Reputation: 133

Compare the new array with the previous one

I have an array with 4 elements

[1, 2, 3, 4]

So far I am printing several arrays, all with different elements in each array, to a limit set by me.

for($i = 0; $i<=100; $i++){//...

Output so far:

[11, 22, 32, 44]
[22, 33, 44, 45]
[12, 24, 25, 31]
[15, 16, 31, 41]
[22, 33, 44, 45]//already exist
[11, 22, 32, 44]//already exist
...

How can I compare an outgoing array to the next one going out and delete the new one if is equal to the previous array?

Upvotes: 0

Views: 83

Answers (1)

nice_dev
nice_dev

Reputation: 17805

You could create a key for an array with the help of implode() and have a set array which has this key. If key is already present, then the current array in iteration is a duplicate one, else it's a new one. Remember to sort the current array as the order of the numbers matter here for proper key check.

<?php

$arr = [
        [11, 22, 32, 44],
        [22, 33, 44, 45],
        [12, 24, 25, 31],
        [15, 16, 31, 41],
        [22, 33, 44, 45],
        [44, 22, 32, 11]
    ];


$set = [];    
foreach($arr as $curr_array){
    sort($curr_array);
    $hash = implode("|",$curr_array);
    if(isset($set[$hash])) echo "Duplicate",PHP_EOL;
    else{
        print_r($curr_array);
        $set[$hash] = true;
    }
}

Demo: https://3v4l.org/EXXRu

Upvotes: 1

Related Questions