Awesome Arrays

Posted on 12. Mar, 2010 by in Basics


At the start of this series of tutorial we learned how to use variable. As you already know variable store information for use for editing and later use. So what happens when you need use a bunch of variable?  Let’s say for example you wanted to store a bunch of ice cream flavors, lets say 8. Using what we learned up to this would take a few lines because we would need to create a new variable to store each new flavor. This is where arrays come in handy.

Arrays can store all types of values from string to integers to many different types we have yet to go over. Lets try out a simple array before we move on to our example:


<?php
//One way to declare an array
$apartment = array("Ground Floor","Floor 1","Floor 2","Floor 3");

//Other way to declare an array
$apartment[0]="Ground Floor";
$apartment[1]="Floor 1";
$apartment[2]="Floor 2";
$apartment[3]="Floor 3";

//Print out a floor name
echo $apartment[2];
?>

Output:

Floor 2

Think of an array as a stack of variables. Instead of creating a bunch of variables, we can simply create an array. The individual values in an array, by it’s index. If your confused you can think of an array as a building with individual values on each floor. If we specify we want to go to index or “floor” 0, remember we always start from zero in PHP, we might find a stored value like “chocolate.” If we where to go to 6th index or “floor” we could find a value like vanilla.


<?php
//Declare our array
$flavors = array("Chocolate ", "Strawberry ", "Butter pecan ", "Neapolitan ",
"Vanilla fudge ripple ", "French vanilla ", "Vanilla ", "Cookies and cream ");

//Edit a flavor
$flavors[0] = "Chocolate chip ";

//Print our flavors
echo "Our Flavors: ";
for($i=0; $i<=7; $i++)
{
echo $flavors[$i];
}
?>

Output:

Our Flavors: Chocolate chip Strawberry Butter pecan Neapolitan Vanilla fudge ripple French vanilla Vanilla Cookies and cream

Wwe can do the same thing more efficiently with arrays. We can easily add other ice cream flavor, and have it print out for us without adding additional lines.