Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the keys for duplicate values in an array

I have the following array:

$myarray = Array("2011-06-21", "2011-06-22", "2011-06-22", "2011-06-23", "2011-06-23", "2011-06-24", "2011-06-24", "2011-06-25", "2011-06-25", "2011-06-26");
var_dump($myarray);

Result:

Array (
    [0] => 2011-06-21
    [1] => 2011-06-22
    [2] => 2011-06-22
    [3] => 2011-06-23
    [4] => 2011-06-23
    [5] => 2011-06-24
    [6] => 2011-06-24
    [7] => 2011-06-25
    [8] => 2011-06-25
    [9] => 2011-06-26
)
  1. Now how can I display the keys with duplicate values? Here the function should NOT return ([0],[9]) since there are no duplicates with the values.
  2. How to find the keys for the same value, eg. for "2011-06-25" it should return [7],[8]
like image 530
schaitanya Avatar asked Jun 23 '11 21:06

schaitanya


People also ask

How do I find duplicate keys in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do I find a key in an array?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

Can array have duplicate keys?

Code Inspection: Duplicate array keysReports duplicate keys in array declarations. If multiple elements in the array declaration use the same key, only the last one will be used, and all others will be overwritten.

How do I count occurrence of duplicate items in array?

To count the duplicates in an array: Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .


1 Answers

I'll answer the second question first. You want to use array_keys with the "search_value" specified.

$keys = array_keys($array, "2011-06-29")

In the example below, $duplicates will contain the duplication values while $result will contain ones that are not duplicates. To get the keys, simply use array_keys.

<?php

$array = array(
  'a',
  'a',
  'b',
  'c',
  'd'
);

// Unique values
$unique = array_unique($array);

// Duplicates
$duplicates = array_diff_assoc($array, $unique);

// Unique values
$result = array_diff($unique, $duplicates);

// Get the unique keys
$unique_keys = array_keys($result);

// Get duplicate keys
$duplicate_keys = array_keys(array_intersect($array, $duplicates));

Result:

// $duplicates
Array
(
    [1] => a
)

// $result
Array
(
    [2] => b
    [3] => c
    [4] => d
)

// $unique_keys
Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)

// $duplicate_keys
Array
(
    [0] => 0
    [1] => 1
)
like image 180
Francois Deschenes Avatar answered Sep 29 '22 20:09

Francois Deschenes