Dec 25, 2014

Array in PHP

Array is a data structure which can store one or more values in a single value. 
 
In here '1,2,3,4,5,6' numbers will assign to one variable. Then we can access all values using that variable. In this array for each value has an ID which is called as array index. using that ID we can access array values. 
 In Php, there are three different arrays. 

  • Numeric Array 
  • Associative array  
  •  Multidimensional array

Numeric Array 

We already know about array index. An Array which is use numeric indexing then that array is a numeric array. By default numeric array index start with zero.You will get idea from this example. 
$myArray = array("H","e","l","l","o","W","o","r","l","d"); // Array intialization
// access the values of created array
echo $myArray[0]; //first value of the array. 0 is the array index
In this example there are ten values that means that array max index is 9. Because numeric array start with 0 (zero). We can get first value using zero th index then second value from first index and so on.We can create numeric array from another way also.
$myArray = array(); // Array intialization
$myArray[0] = "H";
$myArray[1] = "e";
$myArray[2] = "l";
$myArray[3] = "l";
$myArray[4] = "o";
$myArray[5] = "W";
$myArray[6] = "o";
$myArray[7] = "r";
$myArray[8] = "l";
$myArray[9] = "d";
// print the values
echo $myArray[0];
echo $myArray[1];
echo $myArray[2];
echo $myArray[3];
echo $myArray[4];
echo $myArray[5];
echo $myArray[6];
echo $myArray[7];
echo $myArray[8];
echo $myArray[9];

Associative Arrays 

Associative array is similar to numeric array. The difference is the array indexing. In here you can put a string as the index key. In numeric array we used numeric values for indexing. But here not use numeric as an index. 
$myArray = array("fname"=>"Harshana", "lname"=>"Samaranayaka","email"=>"awharshana@gmail.com"); // Array intialization
echo "My first name is ".$myArray["fname"]."<br />";
echo "My last name is ".$myArray["lname"];

Multidimensional Arrays 

In multidimensional array we can use nested array. $myarray[0][1] this means get the first index and inside first index get the second value. Overall Image.
you can see the first index value is another array. That is the multidimensional array. Then check how to implement this kind of array in php.
$person= array("name"=>array("fname"=>"Harshana", "lname"=>"Samaranayaka"),
"position"=>"Student","email"=>"awharshana@gmail.com"); // Array intialization
echo "My first name is ".$myArray["name"]["fname"]."<br />";
echo "My last name is ".$myArray["name"]["lname"];
echo "My Position is ".$myArray["position"];
echo "My email address is ".$myArray["email"];
you can see the 'name' index has an array. 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.