Searching...
Tuesday 2 July 2013

Creating Arrays


Unlike other languages, PHP doesn’t require that you assign a size to an array at creation time. In fact, because it’s a loosely typed language, PHP doesn’t even require that you declare the array before using it, although you’re free to do so. Each approach is introduced here, beginning with the informal variety.
Individual elements of a PHP array are referenced by denoting the element between a pair of square brackets. Because there is no size limitation on the array, you can create the array simply by making reference to it, like this:

$state[0] = "Delaware";

You can then display the first element of the array $state, like this:

echo $state[0];

Additional values can be added by mapping each new value to an array index, like this:

$state[1] = "Pennsylvania";
$state[2] = "New Jersey";
...
$state[49] = "Hawaii";

Interestingly, if you intend for the index value to be numerical and ascending, you can omit the index value at creation time:

$state[] = "Pennsylvania";
$state[] = "New Jersey";
...
$state[] = "Hawaii";

Creating associative arrays in this fashion is equally trivial except that the key is always required. The following example creates an array that matches U.S. state names with their date of entry into the Union:

$state["Delaware"] = "December 7, 1787";
$state["Pennsylvania"] = "December 12, 1787";
$state["New Jersey"] = "December 18, 1787";
...
$state["Hawaii"] = "August 21, 1959";

Creating Arrays with array()

The array() construct takes as its input zero or more items and returns an array consisting of these input elements. Its prototype looks like this:

array array([item1 [,item2 ... [,itemN]]])

Here is an example of using array() to create an indexed array:

$languages = array("English", "Gaelic", "Spanish");
// $languages[0] = "English", $languages[1] = "Gaelic", $languages[2] = "Spanish"

You can also use array() to create an associative array, like this:

$languages = array("Spain" => "Spanish",
"Ireland" => "Gaelic",
"United States" => "English");
// $languages["Spain"] = "Spanish"
// $languages["Ireland"] = "Gaelic"
// $languages["United States"] = "English"

Extracting Arrays with list()

The list() construct is similar to array(), though it’s used to make simultaneous variable assignments (more about variables) from values extracted from an array in just one operation. Its prototype looks like this:

void list(mixed...)

This construct can be particularly useful when you’re extracting information from a database or file. For example, suppose you wanted to format and output information read from a text file named users.txt. Each line of the file contains user information, including name, occupation, and favorite color with each item delimited by a vertical bar. A typical line would look similar to the following:

Nino Sanzi | professional golfer | green

Using list(), a simple loop could read each line, assign each piece of data to a variable, and format and display the data as needed. Here’s how you could use list() to make multiple variable assignments simultaneously:

// Open the users.txt file
$users = fopen("users.txt", "r");
// While the EOF hasn't been reached, get next line
while ($line = fgets($users, 4096))
{
// use explode() to separate each piece of data.
list($name, $occupation, $color) = explode("|", $line);
// format and output the data
printf("Name: %s <br />", $name);
printf("Occupation: %s <br />", $occupation);
printf("Favorite color: %s <br />", $color);
}
fclose($users);

Each line of the users.txt file will be read and the browser output formatted similarly to this:

Name: Nino Sanzi
Occupation: professional golfer
Favorite Color: green

Reviewing the example, list() depends on the function explode() (which returns an array) to split each line into three elements, which explode() does by using the vertical bar ( | ) as the element delimiter. These elements are then assigned to $name, $occupation, and $color.

Populating Arrays with a Predefined Value Range

The range() function provides an easy way to quickly create and fill an array consisting of a range of low and high integer values. An array containing all integer values in this range is returned. Its prototype looks like this:

array range(int low, int high [, int step])

For example, suppose you need an array consisting of all possible face values of a die:

$die = range(1, 6);
// Same as specifying $die = array(1, 2, 3, 4, 5, 6)
//now putting step value of 2:
$even = range(0, 20, 2);
// $even = array(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20);

The range() function can also be used for character sequences. For example, suppose you want to create an array consisting of the letters A through F:

$letters = range("A", "F");
// $letters = array("A", "B", "C", "D", "E", "F");

Testing for an Array

When you incorporate arrays into your application, you’ll sometimes need to know whether a particular variable is an array. A built-in function, is_array(), is available for accomplishing this task. Its prototype follows:

boolean is_array(mixed variable)

This function will return True if the variable is an array, otherwise False.

$states = array("Florida");
$state = "Ohio";
printf("\$states is an array: %s <br />", (is_array($states) ? "TRUE" : "FALSE"));
printf("\$state is an array: %s <br />", (is_array($state) ? "TRUE" : "FALSE"));

Executing this example produces the following:

$states is an array: TRUE
$state is an array: FALSE

0 comments:

Post a Comment

 
Back to top!