PHP: Hash Table Tutorial

,

A keyed list (aka hash-table, dictionary, associative list) in PHP is simply called array. It is constructed using the form “array(key1 => val1, key2 => val2, …)”. Example:

<?php
$x = array("mary" => 19, "jane" => 16);
print_r($x);
?>

Get Values

To get value of a element, use the form “$arr[key]”.

<?php
$x = array("mary" => 19, "jane" => 16);
echo($x["mary"]);
?>

Note that the key should be quoted.

Modify

Modify/Add A Entry

To add a entry, use the form “$arr[key] = val”. If the key exist, old value will be replaced. Otherwise, a new entry will be added

<?php
$x = array("mary" => 19, "jane" => 16);
$x["mary"]=18; // modify a entry
$x["vicky"]=21; // add a entry
print_r($x);
?>

Delete a Entry

To delete a entry, use “unset()”.

<?php
$x = array("mary" => 19, "jane" => 16);
unset($x["mary"]);
print_r($x);
?>

Misc

Key Exists

To check if a key exists, use “array_key_exists”.

<?php
$x = array("mary" => 19, "jane" => 19);
echo array_key_exists("mary",$x);
?>

Get Just Keys

To get just the keys, use “array_keys()”.

<?php
$x = array("mary" => 19, "jane" => 16);
print_r(array_keys($x)); // (0 => mary, 1 => jane)
?>

Get Just Values

To get just the values, use “array_values()”. The function “array_values()” effectively replaces all the keys by numerical indexes starting from 0.

<?php
$x = array("mary" => 19, "jane" => 16);
print_r(array_values($x));
?>

Arrays

Array Operators

Array Functions

blog comments powered by Disqus
2007-11