Thursday, September 2, 2010

PHP Array

An array can store one or more values in a single variable name.

What is an array?
  • When working with PHP, sooner or later, you might want to createmany similar variables.
  •  Instead of having many similar variables, you can store the dataas elements in an array.
  • Each element in the array has its own ID so that it can be easily accessed.
Types of Array:
  1. Numeric Array
  2. Associative Array
  3. Multidimensional Array
1) Numeric Array:
  • A numeric array stores each element with a numeric ID key.
  • There are different ways to create a numeric array:
Example 1
In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");

Example 2
In this example we assign the ID key manually:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";



2) 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 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);


Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";




3) 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.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);

1 comment:

  1. Thanks A Lord For Publish In Your Blog, This Is A Great Things To Learned Many Information. Keep Posting Many Blogs Like This.
    Web portal development company in chennai, Web portal development services in chennai

    ReplyDelete