PHP: Hash Table Tutorial

By Xah Lee. Date:

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));

If you have a question, put $5 at patreon and message me.

  1. PHP Install
  2. PHP Basics
  3. String Syntax
  4. String Operations
  5. Array
  6. Hash Table
  7. Looping Thru Array
  8. Function
  9. Write Package
  10. Send HTML Mail
  11. Send Mail with Attachment
  12. MySQL Database Query