Приглашаем посетить
Лермонтов (lermontov-lit.ru)

Chapter 2.  Working with Arrays

Previous
Table of Contents
Next

Chapter 2. Working with Arrays

When simple variables are just not good enough, arrays come into play (or objects, but that's another topic). The array section in the PHP manual, available at http://php.net/array, lists approximately 80 functions that are helpful. Therefore, this book could be filled with array-related phrases alone. However, not all of these functions are really used often. Therefore, this chapter presents the most important problems you'll have to solve when working with arraysand, of course, solutions for these problems.

There are two types of arrays. The names they are given differ sometimes, but usually arrays are distinguished between numerical arrays and associative arrays. The first type of array uses numerical keys, whereas the latter type can also use strings as keys.

Creating an array can be done in one of two ways:

  • Using the array() function

    $a = array('I', 'II', 'III', 'IV');
    

  • Successively adding values to an array using the variable name and square brackets

$a[] = 'I';
$a[] = 'II';
$a[] = 'III';
$a[] = 'IV';

When using associative arrays, the same two methods can be used; however, this time keys and values must be provided:

$a1 = array('one' => 'I', 'two' => 'II', 'three' =>
  'III', 'four' => 'IV');
$a2['one'] = 'I';
$a2['two'] = 'II';
$a2['three'] = 'III';
$a2['four'] = 'IV';

Arrays can also be nested, when an array element itself is an array:

$a = array(
  'Roman' =>
    array('one' => 'I', 'two' => 'II', 'three' =>
      'III', 'four' => 'IV'),
  'Arabic' =>
    array('one' => '1', 'two' => '2', 'three' =>
      '3', 'four' => '4')
);

Now, the Arabic representation of the number four can be accessed using $a['Arabic']['four'].

Of course, arrays are not only created within a script, but can also come from other sources, including from HTML forms (see Chapter 4, "Interacting with Web Forms") and from cookies and sessions (see Chapter 5, "Remembering Users (Cookies and Sessions)"). But if the array is there, what's next? The following phrases give some pointers.


Previous
Table of Contents
Next