PHP ARRAY

Started by VelMurugan, Apr 28, 2009, 06:46 PM

Previous topic - Next topic

VelMurugan

PHP ARRAY

An array is a way of holding multiple closely-related values, such as the test scores of all students in a class. An array is made up of a key and a value, and the key points to the value.

There are two types of arrays: Indexed array and Associative array. Their difference is in the way the key is specified. Let's look at both of them:

Indexed Array

In an indexed array, the keys are numeric and starts with 0, and the values can be any data type. The following shows two ways of assigning values to an indexed array:

$friends = array("Sophie","Stella","Alice");

This is equivalent to the following:

$friends[0] = "Sophie";
$friends[1] = "Stella";
$friends[2] = "Alice";

Associative Array

In an associative array, the keys are not necessarily numeric, and even when they are numeric, not necessarily in any order. So, when you are putting data into an associative array, you'll need to make sure you specify both the key and the value:

$student_score = array("John"=>80, "Matt"=>90, "May"=>85);

This is equivalent to the following:

$student_score["John"] = 80;
$student_score["Matt"] = 90;
$student_score["May"] = 85;

Multidimensional Array

The arrays in the examples above are 1-dimensional. However, there will be times when multidimensional arrays are desired. What's a multidimensional array? That's when you have arrays of arrays. Let's look at an example below:

$array1 = array (10,15,20);
$array2 = array (110,115,120);
$array3 = array (210,215,220);
$big_array = array ($array1, $array2, $array3);

$big_array is now a 2-dimensional array. For example, if you have the following output code:

print {$big_array[1,2]};

The output would be

120

Remember to use { } when you are accessing the value of a multidimensional array.