Arrays in PHP are sophisticated and more flexible than in many other high-level languages. An array is an ordered set of variables, in which each variable is called an element. Technically, arrays can be either numbered or associative, which means that the elements of an array can be accessed by a numeric index or by a textual string, respectively.

In PHP, an array can hold scalar values-integers, Booleans, strings, or floats-or compound values-objects and even other arrays, and can hold values of different types. In this section, we show how arrays are constructed and introduce several useful array functions from the PHP library.

Creating Arrays

PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use:

$numbers = array(5, 4, 3, 2, 1);
$words = array("Web", "Database", "Applications");
// Print the third element from the array
// of integers: 3
echo $numbers[2];
// Print the first element from the array
// of strings: "Web"
echo $words[0];

By default, the index for the first element in an array is 0. The values contained in an array can be retrieved and modified using the bracket [ ] syntax. The following code fragment illustrates the bracket syntax with an array of strings:

$newArray[0] = "Potatoes";
$newArray[1] = "Carrots";
$newArray[2] = "Spinach";
// Oops, replace the third element
$newArray[2] = "Tomatoes";

Numerically indexed arrays can be created to start at any index value. Often it's convenient to start an array at index 1, as shown in the following example:

$numbers = array(1=>"one", "two", "three", "four");

Arrays can also be sparsely populated, such as:

$oddNumbers = array(1=>"one", 3=>"three", 5=>"five");

An empty array can be created by assigning a variable with no parameters with array( ). Values can then be added using the bracket syntax. PHP automatically assigns the next numeric index-the largest current index plus one-when an index isn't supplied. Consider the following example, which creates an empty array $errors and tests whether that array is empty at the end of the script. The first error added with $errors[] is element 0, the second is element 1, and so on:

$errors = array(  );
// later in the code ..
$errors[] = "Found an error";
// ... and later still
$errors[] = "Something went horribly wrong";
// Now test for errors
if (empty($errors))
  // Phew. We can continue
  echo "Phew. We can continue";
  echo "There were errors";