Location: PHPKode > scripts > Magic Consistent Hash Script > magic-consistent-hash-class/ConsistentHash.example.php
<?php
    require_once("ConsistentHash.class.php");

    function getmicrotime() { 
       list($usec, $sec) = explode(" ", microtime()); 
       return ((float)$usec + (float)$sec); 
    }
    
    $servers = array(
        '1.1.1.1',
        '1.1.1.2',
        '1.1.1.3',
        '1.1.1.4',
        '1.1.1.5',
        '1.1.1.6', 
        '1.1.1.7',
        '1.1.1.8',
        '1.1.1.9'
    );
    
    $objCHash = new ConsistentHash($servers);
	
    // lets look how all keys are loadbalanced in hash array
    $start_time = getmicrotime();
    
    $counters = array();    
    for ($i=0; $i<500; $i++){
        $id = mt_rand(1000,9999999);
        //$id = $i;
        $host = $objCHash->Lookup($id,1);
        
        $counters[$host]++;    
    }
    echo "How they loadbalanced:<br>\n";
    foreach ($counters as $k=>$v){
    	echo $k." - key count:".$v."<br>\n";
    }
    echo "<br>\n";echo "<br>\n";
    
    $end_time = getmicrotime();
    
    echo "time:".($end_time-$start_time); 

    
   
    // example of usage:
    // $data = 'data for cahing';
    // $key = md5($data) - usually key makes by this way
    // $host = $objCHash->Lookup($key);
    // here we got hostname of needed cache server, now we can use native memcached class to connect to it
    // $memcache = new Memcache;
    // $connect = $memcache->connect($host , 11212, 1);
    // $memcache->set($key,$data);
    
    $start_time = getmicrotime();
	$counters = array();    
    for ($i=0; $i<500; $i++){
        $id = mt_rand(1000,9999999);
        //$id = $i;
        $host = (array)$objCHash->Lookup($id,2); // will return 2 items from hash array. 
        //$host = implode(':',$host);
        echo "[".$i."] - ".implode('|',$host)." : ".$id."<br>\n";
        
    }
    $end_time = getmicrotime();
    
   
    
    echo "time:".($end_time-$start_time); 
Return current item: Magic Consistent Hash Script