Tag Archive for 'snippets'

Remove duplicate values from array: array_unique() variations and alternatives

One of my favorite features of PHP is the tremendous wealth of built-in functions that perform all kinds of useful tasks. Practically any basic operation I ever need to do can be done with a simple PHP function call. This was the case when I needed to remove duplicate values from an array of strings. array_unique() to the rescue.

However, it turns out that for simple dupe removal operations, there are alternatives to array_unique() that perform noticeably faster.

To replace array_unique(), try this faster alternative:

array_flip(array_flip($array))

Note that both functions above leave “gaps” in the resulting array; if $array[2] is a dupe and removed, $array[3] does NOT become $array[2]. If you’d like to reindex/reorder the resulting array, try

array_values(array_unique($array))

And here’s a faster alternative: (source)

array_keys(array_flip($array))

If you’d like to remove case insensitive duplicates, try the following function: (source)

function array_iunique($array) {
    return array_intersect_key($array,array_unique(
                 array_map(strtolower,$array)));
}

Or this faster alternative:

function array_iunique($array) {
	return array_intersect_key($array,
                 array_flip(array_flip(array_map(strtolower,$array))));
}

Sorry for the really infrequent updates. 3-4 hour commutes per day and long work hours is killing my free time.

Merry Christmas to all!

If you liked this post, please subscribe to my feed. Thanks for visiting!

PHP: Measuring code execution time

The following code measures the amount of time it takes to execute a chunk of code.

In PHP 4 (source):

$time1 = explode(' ', microtime());
/* your chunk of code here */
$time2 = explode(' ', microtime());
$begintime = $time1[1] + $time1[0];
$endtime = $time2[1] + $time2[0];
$totaltime = $endtime - $begintime;
echo "\n<!-- Executed in $totaltime sec -->\n";

In PHP 5 (source):

$time_start = microtime(true);
/* your chunk of code here */
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "\n<!-- Executed in $time sec -->\n";

My Code

Here you can find code that I have written during my journeys through the intarwebs. Hopefully, people other than myself will find the code useful.

I am very much an amateur programmer. Please let me know if you improve on the code here in any way. Thanks! :)

Conditional GET PHP function
Zenphoto plugin: HTTP Cache Control
Zenphoto plugin: Link Prefetching Hints
Zenphoto plugin: Static Cache Control