Numerically Indexed Arrays

Let’s assume that you’ve been tasked with creating a simple website for a local office supplies company and you’re currently working on the section devoted to paper. One way to manage the various items of stock in this category would be to place them in a numeric array. You can see the simplest way of doing so in following example

<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
print_r($paper);
?>

In this example, each time you assign a value to the array $paper, the first empty location within that array is used to store the value and a pointer internal to PHP is incremented to point to the next free location, ready for future insertions. The familiar print_r function (which prints out the contents of a variable, array, or object) is used to verify that the array has been correctly populated.

The previous code could equally have been written as in previous Example, where the exact location of each item within the array is specified. But, as you can see, that approach requires extra typing and makes your code harder to maintain if you want to insert or remove supplies from the array. So unless you wish to specify a different order, it’s usually better to simply let PHP handle the actual location numbers.

<?php
$paper[0] = "Copier";
$paper[1] = "Inkjet";
$paper[2] = "Laser";
$paper[3] = "Photo";
print_r($paper);
?>

The output from these previous examples are identical, but you are not likely to use print_r in a developed website, so next Example shows how you might print out the various types of paper the website offers using a for loop.

<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
for ($j = 0 ; $j < 4 ; ++$j)
	echo "$j: $paper[$j]<br>";
?>