Arrays

An array is a list of values. If we write $num=5; then $num is not an array. If, however, we write $num[0]=5; then we have created an array. Usually, when we create an array we initialize it to several values. We could do this by writing $toppings=array('sausage','pepperoni','mushrooms','extra cheese'); We have now created an array called $toppings. The array is zero indexed meaning the if we write echo $toppings[0]; it will print out sausage.

There are several built-in functions for dealing with arrays. If we write sort($toppings); then print out $toppings[0] it will print extra cheese. Instead of using a constant for the index (also called subscript) we can use a for loop to print out the entire array;

<?php
$toppings=array('sausage','pepperoni','mushrooms','extra cheese'); 
sort($toppings);
for($i=0;$i<sizeof($toppings);$i++) {
	echo $toppings[$i].' ';
}
echo '<br />'; //end the line
?>

We can also print out all of the toppings using a foreach loop:

foreach($toppings as $key=>$info) {
	echo $info.' ';
}
echo '<br />'; //end the line

The elements of an array do not have to have a numeric index. Consider the following:

$state['MD']='Maryland';
$state['VA']='Virginia';
$state['NY']='New York';
foreach($state as $key=>$info) {
	echo "$key $info<br />";  //prints MD Maryland, etc.
}
In this case a for loop would not work and we would need to use the foreach loop. Also, we must sort this array using asort() NOT sort()
This array could also have been initialized using
$state=array('MD'=>'Maryland', 'VA'=>'Virginia', 'NY'=>'New York');
INDEX, Arrays: Introduction, Create form from array, Arrrays
Next lesson: StringsMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Arrays: Introduction