Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHPGangsta: Doppelte Array-Einträge entfernen
<?php
if (extension_loaded('xdebug')) {
echo "WARNING: xdebug is enabled\n";
}
function _count()
{
$array = array(1, 5, 8, 'Michael', 5, 4, 9, 'Martin', 18, 12, 'Michael', 4, 12);
$counts = array_count_values($array);
foreach ($counts as $value => $counter) {
if ($counter > 1) {
unset($counts[$value]);
}
}
$v = array_keys($counts);
}
function _diff()
{
$array = array(1, 5, 8, 'Michael', 5, 4, 9, 'Martin', 18, 12, 'Michael', 4, 12);
$v = array_diff($array, array_diff_assoc($array, array_unique($array)));
}
function _foreach()
{
$array = array(1, 5, 8, 'Michael', 5, 4, 9, 'Martin', 18, 12, 'Michael', 4, 12);
$index = array();
$duplicate = array();
foreach ($array as $i => $a) {
if (isset($index[$a])) {
unset($array[$index[$a]]);
unset($array[$i]);
unset($index[$a]);
$duplicate[$a] = true;
continue;
}
if (isset($duplicate[$a])) {
unset($array[$i]);
continue;
}
$index[$a] = $i;
}
$v = $array;
}
$data = array();
$functions = array(
'_count',
'_diff',
'_foreach',
);
$res = array();
$mem = array();
foreach( $functions as $k )
{
$iterations = 3;
$rest = array();
$t = memory_get_usage();
//ob_start();
$start = microtime(true);
while (--$iterations) {
$k();
}
$end = microtime(true);
//ob_get_clean();
$res[$k] = $end - $start;
$mem[$k] = (memory_get_usage() - $t) / 1024;
}
echo "results, fastest first:\n";
asort($res);
foreach ($res as $k => $d) {
printf("%-20s %0.10f %0.4f\n", $k, $d, $mem[$k]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment