Arrays

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP-array as a value, you can also quite easily simulate trees.

Explaination of those structures is beyond the scope of this manual, but you'll find at least one example for each of those structures. For more information about those structures, buy a good book about datastructures.

Syntax

Specifying with array()

An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.

A key is either a nonnegative integer or a string. If a key is the standard representation of a non-negative integer, it will be interpreted as such (i.e. '8' will be interpreted as 8, while '08' will be interpreted as '08').

A value can be anything.

Omitting keys. If you omit a key, the maximum of the integer-indices is taken, and the new key will be that maximum + 1. If no integer-indices yet exist, the key will be 0 (zero). If you specify a key that already has a value assigned to, that key will be overwritten.


array( [key =>] value
     , ...
     )
// key is either string or nonnegative integer
// value can be anything
      

Creating/modifying with square-bracket syntax

You can also modify an existing array, by explicitely setting values.

This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable-name in that case.

$arr[key] = value;
$arr[] = value;
// key is either string or nonnegative integer
// value can be anything
      
If $arr doesn't yet exist, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to it. If you want to remove a key/value pair, you need to unset() it.

Useful functions

There are quite some useful function for working with arrays, see the array-functions section.

The foreach control-structure exists specificly for arrays. It provides an easy way to traverse an array.

Examples

The array-type in PHP is very versatile, so here will be some examples to show you the full power of arrays.


// this
$a = array( 'color' => 'red'
          , 'taste' => 'sweet',
          , 'shape' => 'round',
          , 'name'  => 'apple',
          ,            4        // key will be 0
          );

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array( 0 => 'a' , 1 => 'b' , 2 => 'c' )
       

Example 6-4. Using array()


// Array as (property-)map
$map = array( 'version'    => 4
            , 'OS'         => 'Linux'
            , 'lang'       => 'english'
            , 'short_tags' => true
            );
            
// strictly numerical keys
$array = array( 7
              , 8
              , 0
              , 156
              , -10
              );
// this is the same as array( 0 => 7, 1 => 8, ...)

$switching = array(         10 // key = 0
                  , 5    =>  6
                  , 3    =>  7 
                  , 'a'  =>  4
                  ,         11 // key = 6 (maximum of integer-indices was 5)
                  , '8'  =>  2 // key = 8 (integer!)
                  , '02' => 77 // key = '02'
                  , 0    => 12 // the value 10 will be overwritten by 12
                  );
                  


// empty array
$empty = array();           
     

Example 6-5. Collection


$colors = array('red','blue','green','yellow');

foreach ( $colors as $color )
{
    echo "Do you like $color?\n";
}

/* output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
*/
     

Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:

Example 6-6. Collection


foreach ( $colors as $key => $color )
{
    // won't work:
    //$color = strtoupper($color);
    
    //works:
    $colors[$key] = strtoupper($color);
}
print_r($colors);

/* output:
Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)
*/
      

This example creates a one-based array.

Example 6-7. One-based index


$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);

/* output:
Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)
*/        
      

Example 6-8. Filling real array


// fill an array with all items from a directory
$handle = opendir('.');
while ( $file = readdir($handle) ) 
{
    $files[] = $file;
}
closedir($handle); 
     

Arrays are ordered. You can also change the order using differen sorting-functions. See array-functions for more information.

Example 6-9. Sorting array


sort($files);
print_r($files);
     

Because the value of an array can be everything, it can also be another array. This way you can make recursive arrays, and multi-dimensional arrays.

Example 6-10. Recursive and multi-dimensional arrays


$fruits = array ( "fruits"  => array ( "a" => "orange"
                                     , "b" => "banana"
                                     , "c" => "apple"
                                     )
                , "numbers" => array ( 1
                                     , 2
                                     , 3
                                     , 4
                                     , 5
                                     , 6
                                     )
                , "holes"   => array (      "first"
                                     , 5 => "second"
                                     ,      "third"
                                     )
                );
    

     

HIVE: All information for read only. Please respect copyright!
Hosted by hive КГБ: Киевская городская библиотека