user1080247
user1080247

Reputation: 1166

how to check multidimensional array for duplicated value

i have this array and i don't want to remove duplicated values.. i want to check if there are duplicates in the first value or not

( [0] => 1500,[0] => 1111, [0] => 1500)

if there are then return true else return false how to do this ?

Array
(
    [0] => Array
        (
            [0] => 1500
            [1] => first
            [2] => 
            [3] => 
            [4] => 50
            [5] => 
            [6] => 
        )

    [1] => Array
        (
            [0] => 1111
            [1] => second
            [2] => 
            [3] => 
            [4] => 10
            [5] => 
            [6] => 
        )

    [2] => Array
        (
            [0] => 1500
            [1] => third
            [2] => 
            [3] => 
            [4] => 100
            [5] => 
            [6] => 
        )



)

Upvotes: 0

Views: 284

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270607

If you have PHP 5.5+ available, the function array_column() makes it easy to extract the first "column" of the sub-arrays, and feed the resultant array to array_count_values(), which would produce an array of values like [1500] => 2, [1111] => 1, from which you can easily deduce which have > 1.

That would look like:

// PHP 5.5+ only...
// Gets counts of each first sub-array value
$counts = array_count_values(array_column($input_multidimensional_array, 0));
// Test that the array key has > 1

// To check a specific one for duplicates:
if (isset($counts['1500']) && $counts['1500'] > 1) {
   // Yes, it has duplicates.
}

But... Since you do not have PHP 5.5+, you'll have to use some form of loop.

$temp = array();
foreach ($input_multidimensional_array as $sub_array) {
  // A temporary array holds all the first elements
  $temp[] = $sub_array[0];
}
// Count them up
$counts = array_count_values($temp);

// Then use the same process to check for multiples/duplicates:
if (isset($counts['1500']) && $counts['1500'] > 1) {
   // Yes, it has duplicates.
}

In either of those cases, you could also use array_filter() to only return the array from $counts which had multiples.

// Filter to only those with > 1 into $only_duplicates
$only_duplicates = array_filter($counts, function($v) {
  return $v > 1;
});
// To further reduce this only to the _values_ themselves like 1500, 1111
// use array_keys:
$only_duplicates = array_keys($only_duplicates);
// is now array('1500')

Upvotes: 1

Related Questions