Arrays

  • An array in PHP is an ordered map, that maps keys to values.
  • A key is either an integer or a string.
  • Use quotes around a string index (key).
  • Arrays are optimized in several ways, so they can reasonably be used for variety of purposes: array, list (vector), hashtable, dictionary, collection, stack, queue, etc.
  • Trees can be simulated by having another array as a value.
  • Multi-dimensional arrays can be simulated by using other arrays for the values of the outermost array.

Key values

  • TRUE  : 1
  • FALSE  : 0
  • NULL  : "" (empty string)

Creating arrays

  • Arrays are created using array( ), passing it a series of comma-separated key => value pairs.
  • If no key is specified, the new key will be the maximum existing integer index + 1 (or zero by default).
  • If a key is specified that already has a value assigned to it, the existing value will be overwritten.
  • If an array element is assigned but the array does not already exist, the array will be automatically created.

Functions

  • unset (array[key])  : Removes a key-value pair.
  • unset (array)  : Deletes the array.
  • count (array)  : Get the number of elements.
  • sort (array)  : Sort the array elements in ascending order.
  • print_r (array)  : Print the contents of an array.
  • reset (array)  : Set the internal array pointer to the first element; return the first element (by value).
  • next (array)  : Advance the internal array pointer; return the current element (by value).
  • prev (array)  : Rewind the internal array pointer; return the current element (by value).
  • end (array)  : Set the internal array pointer to the last element; return the last element (by value).
  • current (array)  : Return the current element in the array.
  • key (array)  : Return the index of the current element.
  • array_keys (array) :  Return the keys of the specified array as an array.

Examples

$arr1 = array("apple" => "red", 12 => true);
echo $arr1["apple"]; // "red"
echo $arr1[12]; // 1
$arr2 = array("myarray" => array(6 => 5, "a" => 42));
echo $arr2["myarray"][6]; // 5
echo $arr2["myarray"]["a"]; // 42
// Fill an array with all items from a directory.
$handle = opendir('.');
while ($file = readdir($handle)) {
$files[] = $file;
}
closedir($handle);
// Iterate through an array (not by reference).
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
// Iterate through an array (same as using foreach; not by reference).
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
// Iterate through an array (by reference).
$numbers = array('one', 'two', 'three');
foreach (array_keys($numbers) as $key) {
echo "$numbers[$key]
\n";
}