PHP Arrays

What is an Array?

A variable is a storage area holding a number or text. The problem is, a variable will hold only one value.
An array is a data structure that stores one or more values in a single value.

In PHP, there are three kind of arrays:

* Numeric array – An array with a numeric index
* Associative array – An array where each ID key is associated with a value
* Multidimensional array – An array containing one or more arrays

Numeric array:

A numeric array stores each array element with a numeric index.

Imagine that you own a car dealer and you want to store the names of all your cars 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 car names inside of a single variable. This can be done, and we show you how below.

$cars[0]=”Saab”;
$cars[1]=”Volvo”;
$cars[2]=”BMW”;
$cars[3]=”Toyota”;

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 cars. 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;

Associative array:

An associative array, each ID key is associated with a value.

If you wanted to store the age 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 age.

$ages['John'] = “35″;
$ages['Sally'] = “31″;
$ages['Jasmine'] = “32″;

echo “John is ” . $ages['John'] . “<br />”;
echo “Sally is ” . $ages['Sally'] . “<br />”;
echo “Jasmine ” . $ages['Jasmine'] ;

The code above will output:

John is 35
Sally is 31
Jasmine is 32

Multidimensional Arrays:

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.







Related Posts:

Comments are closed.