Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AlexandreBonneau/e979647e19a856b0bf17 to your computer and use it in GitHub Desktop.
Save AlexandreBonneau/e979647e19a856b0bf17 to your computer and use it in GitHub Desktop.
/**
* Return an array containing only the element 'key => value' that are duplicated in the original $array.
* Warning : the generated array DOES NOT respect the order of the original array.
* @param $array
*
* @return array
* @licence Copyright (C) 2015 Alexandre Bonneau
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public static function arrayDuplicates($array) {
$keyArr = [];
$valArr = [];
$dupeArr1 = [];
foreach ($array as $key => $val) {
if (in_array($key, $keyArr)) {
$dupeArr1[$key] = $val;
}
else if (in_array($val, $valArr)) {
$dupeArr1[$key] = $val;
}
$keyArr[] = $key;
$valArr[] = $val;
}
$result = $dupeArr1;
foreach ($dupeArr1 as $key => $val) { //I add the very first key=>value pair for the original array for each key=>value pair found in the array of duplicates
/*
* Note : If the original array has duplicated key=>value elements, the first 'element' is copied that number of times. But duplicate keys in an array is unlikely, so osef ;)
*/
foreach ($array as $oKey => $oVal) {
if ($key === $oKey || $val === $oVal) {
$result[$oKey] = $oVal;
break;
}
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment