2007-11
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); ?>
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.
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); ?>
To delete a entry, use “unset()”.
<?php $x = array("mary" => 19, "jane" => 16); unset($x["mary"]); print_r($x); ?>
To check if a key exists, use “array_key_exists”.
<?php $x = array("mary" => 19, "jane" => 19); echo array_key_exists("mary",$x); ?>
To get just the keys, use “array_keys()”.
<?php $x = array("mary" => 19, "jane" => 16); print_r(array_keys($x)); // (0 => mary, 1 => jane) ?>
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)); ?>
