Array Variables



Prev. Page
Index Page
Next Page

  • In PHP, array variables look just like scalar variables (different from Perl where arrays always start with an "at" symbol (@) and associative arrays (called hashes) start with a percent sign (%).
  • Simple assignment to an array is done using the array() function. This creates an array with 12 items:
    $months = array( "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
    		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ) ;
    
  • Note that the array items are numbered starting with 0 (zero), not 1 (one). So in this case, we have $months[0] (Jan) through $months[11] (Dec). $months[1] is "Feb", not "Jan".
  • You may also assign values directly to an array element. If you do not specify the array index, the next available index is used. This creates an array with 7 elements:
    $days[0] = "Sunday" ;
    $days[1] = "Monday" ;
    $days[2] = "Tuesday" ;
    $days[3] = "Wednesday" ;
    $days[4] = "Thursday" ;
    $days[] = "Friday" ;
    $days[] = "Saturday" ;
    
  • To reference individual array items, use the array name with the index. If you reference an array variable in a double quoted string, you need to surround the variable and index with curly braces.
    print 'Today is ' . $days[1] ;
    print "Tomorrow is {$days[2]}" ;
    print "Yesterday was {$days[$x-1]}" ;
    
  • Performing an operation on each item in an array may be done in a few different ways:
    $languages = array( "C", "C++", "Perl", "PHP", "Visual Basic", "Java" ) ;
    
    // for loop
    for ( $i=0; $i < count($languages); $i++ ) {
    	print "Language: {$languages[$i]}\n" ;
    }
    
    // foreach loop
    foreach ( $languages as $item ) {
    	print "Language: $item\n" ;
    }
    
  • Array indices don't need to be numbers. They may be any valid expression, including strings. Here we use names as array indices and phone extensions as values:
    $days = array( "Jan" => 31, "Feb" => 28, "Mar" => 31, "Apr" => 30, ... ) ;
    
  • In this case, the foreach loop can retrieve both the key and the value for each item:
    foreach ( $days as $month => $number ) {
    	print "There are $number days in $month\n" ;
    }
    
    print 'January has ' . $days["Jan"] . " days.\n" ;
    


Prev. Page
Index Page
Next Page

Copyright © 2003
Henry H. Hartley
All Rights Reserved