| px | top | add code | search | signup | login | help |
<?php
//##################################################################
// this function takes the following arguements
// $arry - the array to be checked
// $dup_free_array - a reference to an array that will be populated
// with the non-duplicate values from $arry
// $dup_array - a reference to an array that will be populated
// with the duplicate values from $arry
//
// it returns a boolean. true if there were duplicates, false
// if there are no duplicates or $arry was not an array
//##################################################################
function seperate_dups($arry, &$dup_free_array, &$dup_array) {
// prevent errors
if (!is_array($arry)) return false;
$dup_free_list = "";
$found_dup = false;
while (list($key, $val) = each($arry)) {
// if it's a duplicate, put it in the all_dups
// array, otherwise, put it in the dup_free_array
if (ereg($val, $dup_free_list)) {
$dup_array[$key] = $val;
$found_dup = true;
}
else {
$dup_free_list .= str_replace(";", "", $val).";";
$dup_free_array[$key] = $val;
}
}
return $found_dup;
}
//################# EXAMPLES ##############################
function print_array($arry, $name = "NO NAME") {
if (!is_array($arry)) {
?>
print_array: <b><?echo $name;?></b>
IS NOT AN ARRAY<br>
<?
return false;
}
?>
<dl>
<dt><b><?echo $name;?></b>
<dd>
<table border=1 cellspacing=0>
<tr>
<td>
<table border=1 cellspacing=0>
<tr>
<td>
<i>
key</i>
</td>
</tr>
<tr>
<td>
<i>
value</i>
</td>
</tr>
</table>
</td>
<?
while (list($key, $val) = each($arry)) {
?>
<td>
<table border=1 cellspacing=0>
<tr>
<td>
<?echo $key;?>
</td>
</tr>
<tr>
<td>
<?echo $val;?>
</td>
</tr>
</table>
</td>
<?
}
?>
</tr>
</table>
</dl>
<?
}
// test cases
$array1 = array(1, 2, 3, 4, 5, 6 ,7, 200, 2, 3);
$array2 = array(
"foo" => "this is foo's value",
"blah" => "this is blah's value",
"beep" => "this is beep's value",
"boom" => "this is foo's value");
$array3 = array(1,2,3,4,5,6,7,100,200);
seperate_dups($array1, &$array1_no_dups, &$array1_dups);
seperate_dups($array2, &$array2_no_dups, &$array2_dups);
seperate_dups($array3, &$array3_no_dups, &$array3_dups);
// print out the results of
print_array($array1, "Array 1");
print_array($array1_no_dups, "Array 1 without duplicates");
print_array($array1_dups, "Array 1's duplicate values");
print_array($array2, "Array 2");
print_array($array2_no_dups, "Array 2 without duplicates");
print_array($array2_dups, "Array 2's duplicate values");
print_array($array3, "Array 3");
print_array($array3_no_dups, "Array 3 without duplicates");
print_array($array3_dups, "Array 3's duplicate values");
?>
Comments or questions?
PX is running PHP 5.2.11
Thanks to Miranda Productions for hosting and bandwidth.
Use of any code from PX is at your own risk.