Page 139 - Open Soource Technologies 304.indd
P. 139
Unit 6: Arrays
The following code will create the same $products array: Notes
$products[0] = ‘Tires’;
$products[1] = ‘Oil’;
$products[2] = ‘Spark Plugs’;
If $products does not already exist, the first line will create a new array with just one element.
The subsequent lines add values to the array.
PHP’s string parsing is pretty clever, you can confuse it. If you are having
trouble with arrays or other variables not being interpreted correctly when
embedded in a double-quoted string, you can put them outside quotes.
Using Loops to Access the Array
Because the array is indexed by a sequence of numbers, we can use a for loop to more easily
display the contents:
for ( $i = 0; $i<3; $i++ )
echo “$products[$i] “;
This loop will give similar output to the preceding code, but will require less typing than
manually writing code to work with each element in a large array. The ability to use a simple
loop to access each element is a nice feature of numerically indexed arrays. Associative arrays
are not quite so easy to loop through, but do allow indexes to be meaningful.
We can also use the foreach loop, specially designed for use with arrays. In this example we
could use it as follows:
foreach ($products as $current)
echo $current.’ ‘;
This stores each element in turn in the variable $current and prints it out.
Following examples will help you to learn array quickly and effectively.
PHP Array Example:
<?php
$array=array(“Hello”,”New”,”World”);
echo count($array);
sort($array);
for($i=0;$i<=4;$i++){
echo $array[$i].”<br/>”;
}
$array=array(“Hello”,”Hi”,”Hei”);
sort($array);
for($i=0;$i<=4;$i++){
echo $array[$i].”<br/>”;
}
LOVELY PROFESSIONAL UNIVERSITY 133