php get duplicate keys in array without using inbuilt function

$arr = array(1, 4, 6, 1, 8, 9, 4, 6);

$unique = array_unique($arr);

$duplicates = array_diff_assoc($arr, $unique);

print_r($duplicates);
Array ( [3] => 1 [6] => 4 [7] => 6 )

4.6
10
Thiagoh 105 points

                                    <?php
/** 
	Examples of these functions:
	array_unique, 
    array_diff_assoc, 
    array_diff, 
    array_keys, 
    array_intersect 
    
    Examle with an array: 
*/
$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));

4.6 (10 Votes)
0
4.22
10

                                    $arr = array(3,5,2,5,3,9);
foreach($arr as $key => $val){
  //remove the item from the array in order 
  //to prevent printing duplicates twice
  unset($arr[$key]); 
  //now if another copy of this key still exists in the array 
  //print it since it's a dup
  if (in_array($val,$arr)){
    echo $val . " ";
  }
}

4.22 (9 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source