Thursday, 27 September 2012

Arrays In PHP Tutorials And Examples

PHP Arrays
An array is capable of storing multiple values in one single variable.

Definition of 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 special variable, which can store multiple values in one single variable. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

Example:
$color1="red";
$color2="blue";
$color3="yellow";


What are Numeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.

1. In the following example the index are automatically assigned (the index starts at 0):
Example:
$colors=array("red","yellow","pink","blue");

2. In the following example we assign the index manually:
Example:
$colors[0]="red";
$colors[1]="yellow";
$colors[2]="pink";
$colors[3]="blue";

Example:
In the following example you access the variable values by referring to the array name and index:

<?php
$colors[0]="red";
$colors[1]="yellow";
$colors[2]="pink";
$colors[3]="blue";

echo $colors[0] . " and " . $colors[1] . " are my favourite colors.";
?>

Output:
red and yellow are my favourite colors.


What are Associative Arrays
An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it.

With associative arrays we can use the values as keys and assign values to them.

Example:
In this example we use an array to assign ages to the different persons:

$marks = array("jack"=>32, "nancy"=>30, "cathy"=>31);

Example:
This example is the same as example 1, but shows a different way of creating the array:

$marks['jack'] = "32";
$marks['nancy'] = "30";
$marks['cathy'] = "31";
The ID keys can be used in a script:

<?php
$marks['jack'] = "32";
$marks['nancy'] = "30";
$ages['cathy'] = "34";

echo "Jack is " . $ages['jack'] . " years old.";
?>
:
Output:
Jack is 32 years old.

No comments:

Post a Comment