Tuesday, July 8, 2014

Array and its types

What is an array?

An array is a data structure that stores one or more similar type of values in a single value.

There are three kinds of array.


1) Numeric array: It is a simple array with a numeric index and values are stored and accessed in linear fashion. It is also called Single dimensional array.
For example:
<?php
$a=array(11,23,45,67);
echo $a['1']."<br/>";
echo $a['2']."<br/>";
?>


2) Associative array: It is an array with strings as index. This stores element values in associatio with key values rather than in a linear fashion.
For example:
<?php
$salaries = array( 
           "Samir" => 2000, 
           "Gauri" => 1000, 
           "Shankar" => 5000
          );

echo "Salary of Samir is ". $salaries['Samir'] . "<br />";
echo "Salary of Gauri is ".  $salaries['Gauri']. "<br />";
echo "Salary of Shankar is ".  $salaries['Shankar']. "<br />";

?>



3) Multidimensional array: It is an array which contains more than one array and values are accessed using multiple indices.
 For example:
<?php
   $marks = array(
        "alex" => array
                (
                "physics" => 35,       
                "maths" => 30,       
                "chemistry" => 39       
                ),
        "rasmila" => array
                (
                "physics" => 30,
                "maths" => 32,
                "chemistry" => 29
                ),
        "shyam" => array
                (
                "physics" => 31,
                "maths" => 22,
                "chemistry" => 39
                )
         );
   /* Accessing multi-dimensional array values */
   echo "Marks for Alex in physics : " ;
   echo $marks['alex']['physics'] . "<br />";
   echo "Marks for Rasmila in maths : ";
   echo $marks['rasmila']['maths'] . "<br />";
   echo "Marks for Shyam in chemistry : " ;
   echo $marks['shyam']['chemistry'] . "<br />";
?>



No comments:

Post a Comment