PHP Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.21

Arrays

Part:   1  2 

PHP Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Non ASCII Characters with MySQL

Inputting Non ASCII Characters

Controlling Response Header Lines

HTTP Request Variables

Sessions

Using Cookies

PHP SOAP Extension

PHP SOAP Extension - Server

Directories, Files and Images

Using MySQL with PHP

... Table of Contents

This chapter describes:

  • What is an array in PHP.
  • Array related functions.

What Is an Array in PHP?

Array: In PHP, an array represents an ordered map of pairs of keys and values. This is different than most of other languages. Basic rules for PHP's array are:

1. An array can be constructed by the array constructor, like:

   $myArray = array(k1=>v1, k2=>v2, ..., kn=>vn);

where k1, k2, ..., and kn are keys of integer type or string type. v1, v2, ..., and vn are values of any data types.

2. The value of a given key in an array can be expressed by the array variable followed by the key in square brackets, like:

   print $myArray[kn];

3. The value of a given key in an array can be modified by an assignment statement, like:

   $myArray[kn] = new_value.

4. A new pair of key and value can be added to an array by an assignment statement, like:

   $myArray[kx] = vx

5. If a string key represents an integer, it will be used as an integer key. So $myArray['7'] is the same as $myArray[7].

6. If the key is missing in an array assignment or an array constructor, an integer key of 0, or the highest integer key plus 1, will be provided.

7. An empty string is also a valid string key, like:

   $myArray[''] = vy; 

8. A pair of key and value can be removed by using the unset() function, like:

   unset($myArray[kn]); 

9. Pairs of keys and values are ordered in an array like a queue. New pairs are always added at the end of the array.

   unset($myArray[kn]); 

Here is a simple script to show you some of these rules:

<?php # ArrayTest.php
# Copyright (c) 2003 by Dr. Herong Yang, http://www.herongyang.com/
# 
   print "\nLibrary hours:\n";
   $libraryHours = array(
      'Monday - Friday'=>'09:00 - 21:00', 
      'Saturday'=>'09:00 - 17:00', 
      'Sunday'=>'closed');
   print_r($libraryHours);
#
   print "\nPrime numbers:\n";
   $primeNumbers = array(3, 5, 7, 11);
   $primeNumbers[] = 13;
   print_r($primeNumbers);
#
   print "\nFruits:\n";
   $fruits[] = 'Apple';
   $fruits[] = 'Orange';
   $fruits[''] = 'Peach';
   $fruits[''] = 'Banana';
   $fruits['G'] = 'Grape';
   $fruits['7'] = 'Pear';
   $fruits[] = 'Fig';
   print_r($fruits);
#
   print "\nFruits array modified:\n";
   unset($fruits[1]);
   $fruits[1] = 'Orange';
   print_r($fruits);
?>

(Continued on next part...)

Part:   1  2 

Dr. Herong Yang, updated in 2006
PHP Tutorials - Herong's Tutorial Notes - Arrays