Home > DeveloperSection > Blogs > Array in PHP

Array in PHP


PHP PHP  Array  Array List 
Ratings:
0 Comment(s)
 127  View(s)
Rate this:

Array in PHP


An array is a data structure that store multiple values in single variable. In PHP to create an array, array() function is used.

<?php

$mobile = array("Samsung", "Nokia", "Micromax"); //$mobile is a single variable that contain many similar types of values.

echo "I like " . $mobile[0] . ", " . $mobile[1] . " and " . $mobile[2] . ".";

?>

 

Output:

I like Samsung, Nokia and Micromax.

 

Basically array are of three types:

Indexed array:

These array can store numbers, object and strings but their index is represented by numbers. Default value of any index is 0.

<?php

$mobile = array("Samsung", "Nokia", "Micromax");

foreach($mobile as $k=>$v)

echo("$k:$v.</br>");

?>

 

Output:

0:Samsung.//default value is 0
1:Nokia.
2:Micromax.

Associative arrays:

 The associative array are similar to index array in terms of functionality but they are different in terms of key/index.

Note: These types of array are not kept inside double quotes else it will not return any value.

<?php

$salary = array("ragini"=>"35000", "Shikha"=>"40000", "Megha"=>"45000");

echo "Shikha salary is " . $salary['Shikha'];

?>

 

Output:

Shikha salary is 40000

 

Multi-dimensional array

 A multi-dimensional array consist one or more arrays. Below is an example in which 3 students marks of three subject are stored in 2-dimensional array.

<?php

         $record = array(

            "Rakesh" => array (

               "Hindi" => 52,

               "English" => 34,        

               "History" => 33

            ),

           

            "salman" => array (

               "Hindi" => 39,

               "English" => 35,

               "History"=> 34

            ),

           

            "Shikha" => array (

               "Hindi" => 37,

               "English" => 29,

               "History" => 31

            )

         );

        

         /* Accessing multi-dimensional array values */

         echo "Marks for Rakesh in History : " ;

         echo $record['Rakesh']['History'] . "<br />";

        

         echo "Marks for salman in English : ";

         echo $record['salman']['English'] . "<br />";

        

         echo "Marks for Shikha in Hindi : " ;

         echo $record['Shikha']['Hindi'] . "<br />";

      ?>

  

 

Marks for Rakesh in History : 33
Marks for salman in English : 35
Marks for Shikha in Hindi : 37


Don't want to miss updates? Please click the below button!

Follow MindStick