Thursday, 20 December 2012

Episode 15: Arrays of PHP



You’ve learned about variables and how they are used, but what if you need to have more than one value assigned to that variable? That, my friend, is a good old-fashioned array. Arrays are nothing more than lists of information mapped with keys and stored under one variable name. For example, you can store a person’s name and address or a list of states in one variable.

Array Syntax
With an array, you can store a person’s name and age under one variable name, like this:

<?php
$husband = array(“firstname”=>”Albert”,
“lastname”=>”Einstein”,
“age”=>”124”);
echo $husband[“firstname”];
?>

Notice how you use => instead of = when assigning values to keys of arrays. This gives you an output of “Albert” and all the values are still stored in the variable name husband. You can also see how you keep track of the information inside the variable with the use of keys such as “firstname” and “lastname.” You can also set an array value in the following way:

<?php
$husband[“firstname”] = “Albert”;
$husband[“lastname”] = “Einstein”;
$husband[“age”] = 124;
?>

This is the equivalent of the previous example.

If you want to simply store a list and not worry about the particular order, or what each value should be mapped to you don’t need to explicitly name the keys; PHP will assign invisible internal keys for processing; numeric integers starting with 0. This would be
set up as follows:

<?php
$flavor[] = “blue raspberry”;
$flavor[] = “root beer”;
$flavor[] = “pineapple”;
?>
These would then be referenced like this:

echo $flavor[0]; //outputs “blue raspberry”
echo $flavor[1]; //outputs “root beer”
echo $flavor[2]; //outputs “pineapple”


            Written by “Shojib”.

No comments:

Post a Comment