PHP Arrays
By David M. Woods
Published September 28, 2006, 9:03 am in News.
This article give an introduction on how to use arrays in PHP. Like all programming languages, arrays in PHP consists of elements; each element consists of a value, and an index. The array-handling features of PHP, however, are especially powerful.
Documentation note: Wherever italics appear, you should substitute your own data, value, or expression.
Index
The index, like the value, can be either a number or a text string.
Numerical indexing could be considered a "classic" or "linear" array. When a text string is used for the index, PHP calls it an "associative" array; it is similar to a "collection" in other development tools, including those by Microsoft.
You need not specify the index value; if you leave it blank, PHP will automatically assign indexes with consecutive numerical integers.
Populating arrays
There are two ways to populate an array. To hard-code values, use the array( ) function. This example shows how to populate an array where no index is specified. (To populate it with literal string values, use quotes. Note that single quotes and double quotes are usually interchangeable.) :
$arrayName = array(NumValue1, NumValue2, NumValue3 [, ...]);
$arrayName = array("StrValue1", "StrValue2", "StrValue3" [, ...]);
To specify index values, use the => operator to separate the index from the value. (The index value, like the element value, must be enclosed in quotes if a string):
$arrayName = array(NumIndex1 => val1, NumIndex2=>val2, NumIndex3=>val3);
$arrayName = array("StrInd1"=>val1, "StrInd2"=>val2, "StrInd3"=>val3);
When populating an array with soft-coded values, the square bracket [ ] operator is preferred. In this example, the index is not specified, and thus PHP will assign an a consecutive integer index:
$arrayName[ ] = value;
In this example, an index value is specified:
$arrayName[NumIndex] = value;
$arrayName["StrIndex"] = value;
Copying arrays
To copy or pass an array:
$NewArray = $OldArray;
Note the absense of brackets. This is also applicable when passing arrays to functions.
The following does NOT copy an array, but rather, it adds another element. In this example, the value to the right of the equal sign happens to be another array; therefore, the array on the left of the equal sign becomes a multi-dimensional array (see "Multi-dimensional-arrays"):
$NewArray[ ] = $OldArray;
Getting data from an array
To retreive a single element:
$arrayName[NumIndex];
$arrayName["StrIndex"];
Note that the square brackets are used both to populate or get individual array elements.
If output format is not important, then a quick and simple way to retreive all array elements is via the print_r( ) function. (The output will use the symbol "=>" to separate the index from the value.) As in copying arrays, the square brackets are not used.
print_r ($arrayName) ;
To programmatically retreive array elements, use the foreach( ) function. This example retreives the element value only:
foreach ($arrayName as $variable) {
any statement using $variable;
}
To retreive both the element value and the index value, create a variable for each and separate them in the function argument using the => operator as follows:
foreach ($arrayName as $index=>$value) {
any statement using $index or $value;
}
Multi-dimensional arrays
In a multi-dimensional array, each element has more than one index. You can populate it using multiple square brackets. Note that empty square brackets on any dimension indicate dynamic numerical index creation:
$arrayName[ ][ ] = value;
$arrayName[ ][index2] = value;
$arrayName[index1][ ] = value;
$arrayName[index1][index2] = value;
Or you can populate it using multiple square brackets and the array( ) function in any combination:
$arrayName[ ]= array(values, ...);
$arrayName[index1]= array(values, ...);
Note that if the value on the right of the equal sign is an array, then the array on the left of the equal sign will become a multi-dimensional array:
$MultiDimArray[ ] = $SingleDimArray;
$MultiDim-Array[index] = $SingleDimArray;
To retrieve an individual element:
$variable = $arrayName[index1][ index2];
Typical data table implementation
Two-dimensional associative arrays are an excellent way to represent data from a database table. Typically, the "inner" dimension represents a row of data, where each element index is the column name and the element value is the field value, and the "outer" dimension is a collection of rows, with a numerical index. Here's an example to retreive selected columns from all rows:
foreach ($TableArray as $RowVariable) {
print $RowVariable["ColumnName1"];
print $RowVariable["ColumnName2"];
print $RowVariable["ColumnName3"];
}
Data table access with Smarty
Smarty is a PHP templating tool which effectively allows you to separate the server-side "back-end" logic from the "front-end" display logic. Smarty contains excellent tools for manipulating a data table as described above. For more information, visit http://smarty.php.net
The foreach function, used in Smarty template files, is modeled after the PHP foreach( ) function, but is slightly different.
This example simply prints, on an HTML page, the key value, and the value from two selected columns. The "$FromVar" must be declared and initialized on the calling PHP page, while the "ItemVar" and "KeyVar" are assigned herein. The square brackets indicate that the "item" and "key" attributes are optional; DO NOT INCLUDE THE SQUARE BRACKETS.
The "from" attribute should represent a two-dimensional array, as described above. The "item" attribute will represent a one-dimensional associative array where index is the column name; note the dot . separating the variable name and column name. The "key" attribute will represent the row index.
{foreach from=$FromVar [item=ItemVar] [key=KeyVar]}
$KeyVar;
$ItemVar.ColumnName1;
$ItemVar.ColumnName2;
{/foreach}
Concatenating array output with other expressions
PHP allows you to easily concatenate variables and other expressions within double quotes. The following example combines a variable with some text:
$x = "Old McDonald";
print "$x had a farm";
However, the following code, which contains an array variable, would result in a parse error:
$x['A'] = "Old McDonald";
print "$x['A'] had a farm";
The correct way to fix this is to surround the array variable with {curly braces}. Curlies can be used to delimit any variable expression when it is enclosed in double quotes:
print "{$x['A']} had a farm";

Comments & Trackbacks
No Comments/Trackbacks for this post yet...
This post has 103 feedbacks awaiting moderation...
Leave a comment