<?php
/*
* Sample code to provide a recursive version of the standard array_unique()
* function.
*
* Sample usage: $uniqarr = array_unique_recursive($array);
* with strict type checking: $uniqarr = array_unique_recursive($array,true);
*
* Open Source Code: If you use this code on your site for public
* access (i.e. on the Internet) then you must attribute the author and
* source web site:
* http://www.pgregg.com/projects/php/code/array_unique_recursive.php
* http://www.pgregg.com/projects/php/code/array_unique_recursive.phps
*
* (c) Paul Gregg, 2008
* 29 June 2008
* http://www.pgregg.com/projects/
*
*/
Function array_unique_recursive($arr, $forcetype=false) {
static $seen = array();
static $depth = -1;
++$depth;
if (is_array($arr)) {
foreach ($arr as $index => $value) {
$type = gettype($value);
if (is_array($value)) {
$arr[$index] = array_unique_recursive($value, $forcetype);
if (count($arr[$index])==0) unset($arr[$index]);
} else {
if ($forcetype && isset($seen[$type][$value]) && $seen[$type][$value]===$value) {
unset($arr[$index]);
} elseif (!$forcetype && isset($seen[$value]) && $seen[$value]==$value) {
unset($arr[$index]);
}
if ($forcetype)
$seen[$type][$value] = $value;
else
$seen[$value] = $value;
}
}
}
if ($depth === 0) $seen = array();
--$depth;
return $arr;
}
show_source(__FILE__);
echo '<hr>';
$a[0][0] = 1;
$a[0][1] = 2;
$a[0][2] = 3;
$a[0][3] = 4;
$a[0][4] = 2;
$a[1][0] = 1;
$a[1][1] = 2;
$a[1][2] = "2";
$a[1][3] = 4;
$a[1][4] = 2;
echo '<br>Input: <pre>', var_export($a, true), '</pre>', "\n\n";
$b = array_unique_recursive($a);
echo '<br>Loose type array_unique_recursive Output: <pre>', var_export($b, true), '</pre>', "\n\n";
$b = array_unique_recursive($a, true);
echo '<br>Strict type array_unique_recursive Output: <pre>', var_export($b, true), '</pre>', "\n\n";
#niklas
$a = array(array('foo'), array('bar'), array('bar'));
echo '<br>Input: <pre>', var_export($a, true), '</pre>', "\n\n";
$b = array_unique_recursive($a);
echo '<br>Loose type array_unique_recursive Output: <pre>', var_export($b, true), '</pre>', "\n\n";
Input: array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 2,
),
1 =>
array (
0 => 1,
1 => 2,
2 => '2',
3 => 4,
4 => 2,
),
)
Loose type array_unique_recursive Output: array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
),
)
Strict type array_unique_recursive Output: array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
),
1 =>
array (
2 => '2',
),
)
Input: array (
0 =>
array (
0 => 'foo',
),
1 =>
array (
0 => 'bar',
),
2 =>
array (
0 => 'bar',
),
)
Loose type array_unique_recursive Output: array (
0 =>
array (
0 => 'foo',
),
1 =>
array (
0 => 'bar',
),
)