Here’s a quick/dirty HashTable implementation for PHP (based on the Java Hashtable API). There are probably better ones, but for what it’s worth … here ya go:
class CHashTable
{
private $_arr = null;
function __construct()
{
$this->_arr = array();
}
function clear()
{
unset( $this->_arr );
$this->_arr = array();
}
function contains($value, $bStrict=false)
{
return in_array($value, $this->_arr, $bStrict);
}
function containsKey($key)
{
return array_key_exists($key, $this->_arr);
}
function containsValue($value, $bStrict=false)
{
return $this->contains($value, $bStrict);
}
function get($key)
{
$value = null;
if( array_key_exists($key, $this->_arr) )
{
$value = $this->_arr[$key];
}
return $value;
}
function isEmpty()
{
return ($this->size()<=0); } function keys() { return array_keys($this->_arr);
}
function put($key, $value)
{
$this->_arr[$key] = $value;
}
function putAll($arr)
{
if( $arr!==null )
{
if( is_array($arr) )
{
$this->_arr = array_merge($this->_arr, $arr);
}
else if( $arr instanceof CHashTable )
{
$this->_arr = array_merge($this->_arr, $arr->_arr);
}
}
}
function remove($key)
{
unset( $this->_arr[$key] );
}
function size()
{
return count($this->_arr);
}
function toString()
{
return print_r($this->_arr, true);
}
function values()
{
return array_values($this->_arr);
}
}
The term “hashtable” may be a little loose here. There is no hashing or indexing done to increase performance. The purpose here was to have some PHP object class to mimic the behavior of a Java Hashtable; it is really use an API wrapper around some PHP associative array. It makes my life easier when porting code.
There may be some issues here, I haven’t really put it through it’s paces yet. I’m writing some database code and needed a base class for data objects that behaves like a Hashtable.
If you have any constructive comments/suggestions, let me know. As always, the commenting rules apply…