1

I working on a function which filters a multi dimensional array, if the successive arrays have same value, I need to remove the arrays in between and get only the first and last of the successive arrays with duplicate values.

I cant figure out how to do this.

Hope you can help me.

Thanks.

SAMPLE CODE

function removeDuplicates($array){
    $result = [];
    $count = 0;
    $firstValue = null;

    for ($i = 0; $i < count($array); $i++) {

        if($array[$i]['id'] == firstValue){

            $result[] = $array[$i]);

        }else{

            // do action

        }

    }

    return $array;

}

Sample Array

Array ( 
    [0] => Array ( 
        [key] => 0 
        [value] => 25 
        ) 
    [1] => Array ( 
        [key] => 1 
        [value] => 25 
        ) 
    [2] => Array ( 
        [key] => 2 
        [value] => 25 
        ) 
    [3] => Array ( 
        [key] => 3 
        [value] => 33 
        )    
    [4] => Array ( 
        [key] => 4 
        [value] => 45 
        ) 
    [5] => Array ( 
        [key] => 5 
        [value] => 66 
        ) 
    [6] => Array ( 
        [key] => 6 
        [value] => 66 
        ) 
    [7] => Array ( 
        [key] => 7 
        [value] => 66 
        ) 
    [8] => Array ( 
        [key] => 8 
        [value] => 66 
        ) 
    [9] => Array ( 
        [key] => 9 
        [value] => 55 
        ) 
    )

Here the first 3 arrays have same values (25), I need to remove the 2nd array and retain the 1st and 3rd, also with the 6th to 9th only retain the 6th and 9th array.

Expected Result

Array ( 
    [0] => Array ( 
        [key] => 0 
        [value] => 25 
        )  
    [2] => Array ( 
        [key] => 2 
        [value] => 25 
        ) 
    [3] => Array ( 
        [key] => 3 
        [value] => 33 
        )    
    [4] => Array ( 
        [key] => 4 
        [value] => 45 
        ) 
    [5] => Array ( 
        [key] => 5 
        [value] => 66 
        ) 
    [8] => Array ( 
        [key] => 8 
        [value] => 66 
        ) 
    [9] => Array ( 
        [key] => 9 
        [value] => 55 
        ) 
    )
2
  • Do you want to preserve the keys? Commented Jun 27, 2019 at 3:35
  • yes please..... Commented Jun 27, 2019 at 3:40

4 Answers 4

1

Try this:

$array = [
        ["key" => 0, "value" => 25],
        ["key" => 1, "value" => 25],
        ["key" => 2, "value" => 25],
        ["key" => 3, "value" => 33],
        ["key" => 4, "value" => 45],
        ["key" => 5, "value" => 66],
        ["key" => 6, "value" => 66],
        ["key" => 7, "value" => 66],
        ["key" => 8, "value" => 66],
        ["key" => 9, "value" => 55],
];

for ($i = 0; $i < count($array); $i++) {
    if (!isset($array[$i])){
        continue;
    }
    if ($array[$i]['value'] == $array[$i+1]['value']) {
        $j = 1;
        while ($array[$i]['value'] == $array[$i+$j+1]['value']) {
            unset($array[$i+$j]);
            $j += 1;
        }
    }
}

print_r($array);

Since you need to preserve the keys, for loop will throw a notice when an element is not set. This is why we first check if an element exists.

Then the loop looks for two identical values that are consecutive i.e. $i and $i+1. Once it finds them, it enters a while loop to test for 3 or more consecutive identical values. It will only unset a consecutive item if there is at least one occurrence before it and one after it. For example, it will delete $i+2 only if $i+3 is identical.

Hope this helps!

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

3 Comments

hi, thanks for the answer, I test your code with my sample array only the first successive duplicates(values with 25) are working, but array with values of 66 is not working..
Yeah it is a mess ... sorry for that ... while I try to fix it. :p
I think it's fixed now. @user123
1

You can approach this as

$r = [];
$lastKey   = '';
foreach($array as $k => $v){ 
  if(in_array($v['value'], array_column($r, 'value'))){
    $lastKey = $v['key'];
  }else{
    if($lastKey && !in_array($lastKey, array_column($r, 'key'))){
        end($r);
        $r[] = [ 'key' => $lastKey, 'value' => $r[key($r)]['value']];
    }
    $r[]       = [ 'key' => $v['key'] , 'value' => $v['value'] ]; 
    $lastKey     = $v['key'];
  }
}

https://3v4l.org/f6FQv

5 Comments

Hi, sir can you not remove the the "key" inside the array
@user123 the key($r) is getting the last key of the array , means the last element array, try to execute this code.
@user123 refer to this one : php.net/manual/en/function.key.php
$array = [ ["key" => 0, "value" => 25], ["key" => 2, "value" => 25], ["key" => 3, "value" => 33], ["key" => 4, "value" => 45], ["key" => 5, "value" => 66], ["key" => 8, "value" => 66], ["key" => 9, "value" => 55], ]; I mean the output should look like this..sorry
@user123 solution has been updated for the desired result.
0

Here is the solution: Your array is something like this:

$array = [
            ["key" => 0, "value" => 25],
            ["key" => 1, "value" => 25],
            ["key" => 2, "value" => 25],
            ["key" => 3, "value" => 33],
            ["key" => 4, "value" => 45],
            ["key" => 5, "value" => 66],
            ["key" => 6, "value" => 66],
            ["key" => 7, "value" => 66],
            ["key" => 8, "value" => 66],
            ["key" => 9, "value" => 55],
        ];

first, find the first and last occurrence of each value. You need a method that travels through the array and find the exact value. Look at this:

function search($search, $array)
    {
        foreach ($array as $key => $val) {
            if ($val['value'] === $search) {
                return $key;
            }
        }

        return null;
    }

Running $firstOccurrence = search(25, $array) will find the first occurrence of 25.

Now, for finding the index of the last occurrence, we should reverse array to traveling from the end of the array. So $lastOccurrence = search(25, array_reverse($array, true)) will find last occurrence index of 25.

Ok, When we process each value, so, We should not process it again. So we need an array which will hold values which are processed.

Final Code:

function testArray()
    {
        $array = [
            ["key" => 0, "value" => 25],
            ["key" => 1, "value" => 25],
            ["key" => 2, "value" => 25],
            ["key" => 3, "value" => 33],
            ["key" => 4, "value" => 45],
            ["key" => 5, "value" => 66],
            ["key" => 6, "value" => 66],
            ["key" => 7, "value" => 66],
            ["key" => 8, "value" => 66],
            ["key" => 9, "value" => 55],
        ];
        $processedItems = [];
        $newArray = [];
        foreach ($array as $index => $item) {
            if (in_array($item["value"], $processedItems))
                continue;
            $processedItems[] = $item["value"];
            $firstIndex = search($item["value"], $array);
            $lastIndex = search($item["value"], array_reverse($array, true));
            $newArray[$firstIndex] = $array[$firstIndex];
            if ($firstIndex != $lastIndex)
                $newArray[$lastIndex] = $array[$lastIndex];
        }
        print_r($newArray);
    }

    function search($search, $array)
    {
        foreach ($array as $key => $val) {
            if ($val['value'] === $search) {
                return $key;
            }
        }

        return null;
    }

1 Comment

thanks for the answer sir,, there's error in this line $firstIndex = $this->search($item["value"], $array); Uncaught Error: Using $this when not in object context
-1

Please try this hope it's work

for ($i = 0; $i < count($array); $i++) {
    if ($array[$i]['value'] == $array[$i+1]['value']) {
        $j = 1;
        while ($array[$i]['value'] == $array[$i+$j+1]['value']) {
            echo $array[$i]['value'].'==='.$array[$i+$j+1]['value'];
            unset($array[$i+$j]);
            $j += 1;
        }
    }
}

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.