PHP Array

Posted on November 5 2009 by zemog

What is an Array?

A variable is a storage area holding a value either text or number. The problem is, a variable will hold only one value.

An array is a special variable, which can store multiple values in one single variable.

If you have a list of items such as friends’ names, storing the names in single variables could look like this:

$friend1="Felix";
$friend2="Noel";
$friend3="hans";

The approach above is still acceptable if you only have a few data but if you will have a lot of data like in the real application, that approach is not proper. Thus, you need arrays.

In an array, the script above will be like this:

$friend[0]="Felix";
$friend[1]="Noel";
$friend[2]="hans";

Another way to create an array is like this:

$friend =array("Felix","Noel","hans");

In the above example, if you want to display the first name in the array you will have something like this:

echo $friend[0];

Going back to the single variable above:

$friend1="Felix";
$friend2="Noel";
$friend3="hans";

Just imagine if there are 1,000 on the list and you want to display all of it. If you are using array you will only have something like this:

for ($x=0; $x<1000; $x++)
{
echo $friend[$x];
}

Note: Of course you can use the sizeof function for array but that is another tutorial


Share This Post

One Response to “PHP Array”

  1. Borellus says:

    Great little tutorial :)