Star Hoster
Photoshop Tutorials
Anonymous Web Surfing
Funny Jokes
Myspace Friends
Open Treasure Chest
Building in Paradise


July 2, 2006

PHP Arrays

Filed under: Intro PHP Tutorials — phpdeveloper @ 1:12 am

Arrays

An array is a data structure that stores one or more values in a single value. For experienced programmers it is important to note that PHP’s arrays are actually maps ,each key is mapped to a value.

Numerically Indexed Array

If this is your first time seeing an array, then you may not quite understand the concept of an array. Imagine that you own a business and you want to store the names of all your employees in a PHP variable. How would you go about this?

It wouldn’t make much sense to have to store each name in its own variable. Instead, it would be nice to store all the employee names inside of a single variable. This can be done, and we show you how below.

PHP Code:

$employee[0] = “Mannie”;
$employee[1] = “Ramon”;
$employee[2] = “Maya”;

In the above example we made use of the key / value structure of an array. The keys were the numbers we specified in the array and the values were the names of the employees. Each key of an array represents a value that we can manipulate and reference. The general form for setting the key of an array equal to a value is:

$array[key] = value;

If we wanted to reference the values that we stored into our array, the following PHP code would get the job done.

PHP Code:

echo $employee[0];
echo “
”;
echo $employee[1];

Display:

Mannie
Ramon

PHP arrays are quite useful when used in conjunction with loops, which we will talk about in a later lesson. Above we showed an example of an array that made use of integers for the keys (a numerically indexed array). However, you can also specify a string as the key, which is referred to as an associative array.

Associative Array

In an associative array a key is associated with a value. If you wanted to store the salaries of your employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

PHP Code:

$salaries[”Mannie”] = 12000;
$salaries[”Ramon”] = 8000;
$salaries[”Maya”] = 6000;

echo $salaries[”Mannie”];
echo $salaries[”Ramon”]

Display:

12000
8000

Once again, the usefulness of arrays will become more apparent if you have knowledge of for and while loops.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.