-9

I have a array like this:

$array = array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'red', 4 => 'red');

and I want to display all the array keys where the values are similars.

Red - 3, 4

Thanks!

swidmann
  • 2,787
  • 1
  • 18
  • 32

2 Answers2

0

You can use the below code

$array = array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'red', 4 => 'red');

// temp array to store unique values
$unique_values = array();
// temp array to store duplicate values
$dup_values = array();

// looping through each value in array
foreach($array as $key=>$value)
{
// If the value is not in unique value i am addig it, if it is then its duplicate so i am adding the keys of duplicate value in $dup_values array
if(!in_array($value, $unique_values))
{
    $unique_values[] = $value;
}
else
{
    $dup_values[$value] = array_keys($array, $value);
}
}

// displaying $dup_values
var_dump($dup_values);
vikramp
  • 46
  • 3
0

this is a way to achieve the task (good execution time +good memory usage):

$array = array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'red', 4 => 'red');

$value_keys = array();
$dup_values = array();

// looping through each value in array
foreach($array as $key=>$value)
{
//reduce the array in the format value=>keys
    $value_keys[$value][]=$key ;
}
//find the duplicate values
foreach($value_keys as $k=>$v){

    if(count($v)>1)
        $dup_values[$k]=$v;
    unset($value_keys[$k]);//free memory
}


// displaying $dup_values
var_dump($dup_values);

output:

array(1) {
  ["red"]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    int(4)
  }
}
Elementary
  • 1,443
  • 1
  • 7
  • 17