PHP: Hash Table
What is PHP Hash Table
PHP array, also function as a list of key value pairs. (aka hash-table, dictionary, associative list)
Creating a Hash Table
array(key1 => value1, key2 => value2, etc)
<?php $x = array("aa" => 19, "bb" => 16); print_r($x); # Array ( [aa] => 19 [bb] => 16 ) ?>
Get Values
To get value of a element, use the form
$arr[key]
<?php $x = array("aa" => 19, "bb" => 16); echo($x["aa"]); # 19 ?>
Note that the key should be quoted.
Add A Entry or Modify
$arr[key] = val
If the key exist, old value is replaced. Otherwise, a new entry is added.
<?php $x = array("aa" => 1, "bb" => 2); $x["aa"]=18; print_r($x); # Array ( [aa] => 18 [bb] => 2 ) ?>
Delete a Entry
To delete a entry, use unset()
<?php $x = array("aa" => 1, "bb" => 2); unset($x["aa"]); print_r($x); # Array ( [bb] => 2 ) ?>
Key Exists
To check if a key exists, use array_key_exists
<?php $x = array("aa" => 2, "bb" => 9); echo array_key_exists("bb",$x); # 1 ?>
Get Just Keys
To get just the keys, use array_keys()
<?php $x = array("aa" => 9, "bb" => 6); print_r(array_keys($x)); # Array ( [0] => aa [1] => bb ) ?>
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("aa" => 19, "bb" => 16); print_r(array_values($x)); # Array ( [0] => 19 [1] => 16 ) ?>