Changes

Jump to: navigation, search

PHP Arrays

1,661 bytes added, 17:08, 1 June 2007
no edit summary
The elements in a PHP array using a numberical key are accessed by referencing the variable contain ing the array, followed by the index into array of the required element enclose din square brackets ([]). We can extend our previous example to display the value contained in the second element of the array (remmeber that the index is zero based so the first element is element 0:
 
<pre>
<?php
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
echo $colorArray[1];
?>
</pre>
 
The above ''echo'' command will output the value in index postion 1 of the array, in this case the string "Yellow".
 
== Creating an Associative Array ==
 
As described earlier an associative array assigns names to postions in the array. This provides a more ''human friendly'' way to access arrasy elements that the numerical key approach outlined above. Once again the ''array()'' function is used to create the array, with option arguments to pre-initialize the array elements. In the case of associative arrasy the arguments are of the form ''key=>value'' where key is the name by which the elemt will be referenced, and value is the value to be stored in taht position in the array.
 
Suppose we are creating an array to store bank customer information. We can assign a key name to each elelemt in the array as follows:
 
<pre>
<?php
$customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');
?>
</pre>
 
== Accessing Elements of an Associative Array ==
 
Now that we have created an associative array and assigned names to each element we can use those names to access the corresponding array values. We can, therefore extend our previous example to extract the customer name from our ''$customerArray'':
 
<pre>
<?php
$customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');
 
echo $customerArray['customerName'];
?>
 
The result will be the customer name "John Smith" appearing in the browser window.

Navigation menu