0

I have more than 4 arrays in single variable as shown below

$myArray = Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas  )Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas ) Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas )

Now i need to compare each and every array of [2] index.

If second index ([2] => USA) is present in some other array then delete duplicate array.

Finally the arrays should look like this

Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas ).

I have tried this but not able to sort it out.

$myArray = array_map("unserialize", array_unique(array_map("serialize", $myArray)));

Is there any way?

2
  • i have edited my question. Array looks like as edited, it does not contain any comma's to separate arrays Commented Nov 13, 2017 at 12:07
  • @DPS In php array elements are separated by commas, but when you use print_r to output an array, it only shows a dummy readable version of an array, which is not a valid syntax for PHP. In php, so you need to use var_export to output an executable array. Here is a demo with print_r and var_export see for your self. It is the same array but print_r removes the commas and quotations. Commented Nov 13, 2017 at 14:10

2 Answers 2

1

You can use a foreach loop for this, like DEMO:

$match = [];
foreach($myArray as $key => $value)
{
    if(!in_array($value[2], $match))
    {
        $match[] = $value[2];
        continue;
    }
    unset($myArray[$key]);
}

This will remove all of the arrays which have duplicate value for [2]

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

Comments

0

You need to iterate through your array with two loops and check the second index value in each of the inner arrays and if there is a duplicated value you can just unset the second one.

Here is a piece of code that should do well:

<?php

for($i=0; $i < count($myArray); $i++) {
    for($j=$i+1; $j < count($myArray); $j++) {
        if ($myArray[$i][2] == $myArray[$j][2]) {
            unset($myArray[$j][2]);
        }
    }
}

P.S: The code is not tested and may need some modifications, but you could get the main idea.

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.