<?php
class
HashTable
{
private
$buckets
;
private
$size
= 12;
public
function
__construct(){
$this
->buckets =
new
SplFixedArray(
$this
->size);
}
private
function
hashfunc(
$key
){
$strlen
=
strlen
(
$key
);
$hashval
= 0;
for
(
$i
= 0;
$i
<
$strlen
;
$i
++){
$hashval
+=ord(
$key
[
$i
]);
}
return
$hashval
%12;
}
public
function
insert(
$key
,
$value
){
$index
=
$this
->hashfunc(
$key
);
if
(isset(
$this
->buckets[
$index
])){
$newNode
=
new
HashNode(
$key
,
$value
,
$this
->buckets[
$index
]);
}
else
{
$newNode
=
new
HashNode(
$key
,
$value
,null);
}
$this
->buckets[
$index
] =
$newNode
;
}
public
function
find(
$key
){
$index
=
$this
->hashfunc(
$key
);
$current
=
$this
->buckets[
$index
];
echo
"</br>"
;
var_dump(
$current
);
while
(isset(
$current
)){
if
(
$current
->key==
$key
){
return
$current
->value;
}
$current
=
$current
->nextNode;
}
return
NULL;
}
}
class
HashNode{
public
$key
;
public
$value
;
public
$nextNode
;
public
function
__construct(
$key
,
$value
,
$nextNode
= NULL){
$this
->key =
$key
;
$this
->value =
$value
;
$this
->nextNode =
$nextNode
;
}
}
$ht
=
new
HashTable();
$ht
->insert(
'Bucket1'
,
'value1'
);
$ht
->insert(
'Bucket2'
,
'value2'
);
$ht
->insert(
'Bucket3'
,
'value3'
);
echo
$ht
->find(
'Bucket1'
);
?>