Creating an Array

Posted on Updated on

Image result for NamespacesCreating an Array

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 in this section, 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”;

The array() construct, discussed next, is a functionally identical yet somewhat more formal means for creating arrays. 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 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|professionalgolfer|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.(The explode() function is formally introduced in Chapter 9.) These elements are then assigned to $name,$occupation, and $color. At that point, it’s just a matter of formatting for display to the browser.

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)

But what if you want a range consisting of solely even or odd values? Or a range consisting of values solely divisible by five? The optional step parameter offers a convenient means for doing so. For example, if you want to create an array consisting of all even values between 0 and 20, you could use a

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:

booleanis_array(mixed variable)

The is_array() function determines whether variable is an array, returning TRUE if it is and FALSE otherwise. Note that even an array consisting of a single value will still be considered an array. An example follows:

$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

For more details and queries please feel free to email, visit or call us. Wishing you the very best for all your future endeavors.

Helpline: 9814666333, 8699444666

Email:info@technocampus.co.in

**************************************************************************************************************

Please fill the FORM and we shall contact you soon.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s