Merge "Rename Image namespace to File for 'be' locale"
[lhc/web/wiklou.git] / includes / ArrayUtils.php
1 <?php
2
3 class ArrayUtils {
4 /**
5 * Sort the given array in a pseudo-random order which depends only on the
6 * given key and each element value. This is typically used for load
7 * balancing between servers each with a local cache.
8 *
9 * Keys are preserved. The input array is modified in place.
10 *
11 * Note: Benchmarking on PHP 5.3 and 5.4 indicates that for small
12 * strings, md5() is only 10% slower than hash('joaat',...) etc.,
13 * since the function call overhead dominates. So there's not much
14 * justification for breaking compatibility with installations
15 * compiled with ./configure --disable-hash.
16 *
17 * @param $array The array to sort
18 * @param $key The string key
19 * @param $separator A separator used to delimit the array elements and the
20 * key. This can be chosen to provide backwards compatibility with
21 * various consistent hash implementations that existed before this
22 * function was introduced.
23 */
24 static function consistentHashSort( &$array, $key, $separator = "\000" ) {
25 $hashes = array();
26 foreach ( $array as $elt ) {
27 $hashes[$elt] = md5( $elt . $separator . $key );
28 }
29 uasort( $array, function ( $a, $b ) use ( $hashes ) {
30 return strcmp( $hashes[$a], $hashes[$b] );
31 } );
32 }
33 }