PHP Arrays

Today we will learn a new concept of arrays in this PHP Arrays tutorial.

  • What are arrays?
    • First find an answer for the following question. What will you do if you are asked to store 4 numbers and then display them?
    • The answer is very simple, you will declare 4 variables, assign values to them and then use echo() function to display them.
    • Now answer the following question. What will you do if you are asked to store 400 numbers and display them at once?
    • No, this is very difficult using variables because it will take a long time, memory and a lot of manual work to complete the task.
    • Arrays are very useful in such situations.
    • Array is a data structure that stores one or more similar type values in a single variable.
    • You can use arrays when you want to store similar type values that are more in number.
    • Array stores each value assigned to it at an index number starting from zero.
    • I mean if we assigned values “One”, ”Two”, “Three” to an array, it will assign value “One” to the index number 0, then it will assign value “Two” to the index number 1 and value “Three” to the index number 2 and so on if more values are assigned.
    • The index numbers make it easy to access the values from array.
    • The values stored in arrays can also be accessed at once using a loop. Mostly for loop is used for the same.
    • In PHP we have three types of arrays:
      1. Numeric Arrays
      2. Associative Arrays
      3. Multidimensional Arrays
    • Let us have a look on each type of array:
  • Types of Array:
    1. Numeric Arrays:
      • Numeric arrays are simple arrays with a numeric index.
      • These arrays are also called as indexed arrays.
      • The values stored in it are accessed in linear fashion.
      • These arrays can store any type of values i.e. strings, integers, floats, objects but their indexes are always integer numbers.
      • By default the index in arrays start with zero (0).
      • These arrays are created using array() function.
      • Syntax of creating an array:
      • Variable_name=array(value1, value2, value3,…);
      • Example for it is shown below:
      • $flowers=array(“Rose”,”Mogra”,”Merrygold”);
      • In the above example we have created an array of flowers.
      • In this array the values “Rose”, “Mogra” and “Merrygold” will be given indexes 0, 1 and 2 respectively.
      • These values can be accessed when needed using the name of array and index of the particular value, like “Rose” can be accessed using $flowers[0], “Merrygold” can be accessed using $flowers[2] and “Mogra” can be accessed using $flowers[1].
      • For accessing values from array the indexes are written in square brackets.
      • If we want to access all the values at once we can use loops.
      • There is another method to create an array as shown below:
      • $flowers[0]=”Rose”;
        $flowers[1]=”Mogra”;
        $flowers[2]=”Merrygold”;
      • The array $flowers can also be created using the above shown method, by manually assigning values to the indexes of the array.
      • Let us see an example to demonstrate an Indexed array:
      • To demonstrate it, we need to create a new folder named arrays in the htdocs folder in xampp folder located in C drive. Then open a new notepad++ document and save it as index.php in the newly created arrays folder.
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Arrays</title>
        </head>
        <body>
        <h3>Demonstration of Indexed Arrays</h3>
        
        <?php
        	//first method of creating indexed array
        	$nos=array(10,20,30,40,50);
        	
        	echo "<br><strong>Numbers in nos array are:</strong><br>";
        	//using for loop to access all the values of array at once
        	for($i=0;$i<5;$i++)
        	{
        		echo "<strong>".$nos[$i]."</strong><br>";
        	}
        	
        	//another method of creating indexed array
        	  $prod[0]="UPS";
        	  $prod[1]="Keyboard";
        	  $prod[2]="Mouse";
        	  
        	echo "<br><br><strong>Products in prod array are:</strong><br>";
        	//we can also use foreach loop to access all the values of array at once
        	foreach($prod as $x)
        	{
        		echo "<strong>".$x."</strong> <br>";
        	}
        ?>
        </body>
        </html>
        
      • In the above code, we have used 2 methods to create array.
      • These array elements can be accessed individually as well as in loops as shown above.
      • The first element of $nos array can be accessed as $nos[0] and so on.
      • The output is shown below:
      • indexed_arrays_output
        fig 1

    2. Associative Arrays:
      • The associative arrays are very similar to indexed arrays with respect to their function but they use strings as index and not numbers.
      • These strings that are used for indexing in associative arrays are called keys.
      • The keys and values associated with it are given during the creation of the array.
      • Syntax of associative array is given below:
      • Variable_name=array(“key1”=>value1,”key2”=>value2,”key3”=>value3,…);
      • Here, you can have values of similar types like integers, strings, float etc but the keys will be of strings.
      • These arrays are used in those places where an association is given more importance.
      • Suppose we want to store marks secured by students in their test, we can store it in associative array as shown below:
      • $marks=array(“Amol”=>80,”Rahul”=>78,”Rohan”=>68);
      • Here, the key Amol is associated to marks 80, key Rahul is associated to marks 78 and key Rohan is associated to marks 68.
      • Here from the key=>value pair itself we can understand that in the array $marks, Amol has secured marks 80, Rahul has secured marks 78 and so on.
      • The above array can also we created in another way shown below:
      • $marks[‘Amol’]=80;
        $marks[‘Rahul’]=78;
        $marks[‘Rohan’]=68;
        
      • The keys are written in square brackets, thus each value is associated with the key manually.
      • Let us see an example to demonstrate the associative arrays:
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Arrays</title>
        </head>
        <body>
        <h3>Demonstration of Associative Arrays</h3>
        
        <?php
        	//first method of creating associative array
        	$salary=array("Michael"=>15000,"Robbin"=>10000,"Pratik"=>9000,"Kartik"=>9000);
        	
        	echo "Salary of Robbin = <strong>Rs.".$salary["Robbin"]."/-</strong><br><br>";
        	
        	//displaying all key=>value pairs using foreach loop
        	echo "All key value pairs of salary array are as follows:<br>";
        	foreach($salary as $s=>$s_value)
        	{
        		echo "<strong>".$s."=>".$s_value."</strong><br>";
        	}
        
        	//another method of creating associative array
        	$profession['Margaret Cruz']="Software Engineer";
        	$profession['Victor Dsouza']="Mechanical Engineer";
        	$profession['Sharlet Fernandes']="Cardiac Surgeon";
        	
        	//displaying values in array profession 
        		echo "<br><strong>Professions:</strong><br>";
        		echo "<strong>Profession of Margaret Cruz = ".$profession['Margaret Cruz']."</strong><br>";
        		echo "<strong>Profession of Victor D'Souza= ".$profession["Victor Dsouza"]."</strong><br>";
        		echo "<strong>Profession of Sharlet Fernandes = ".$profession['Sharlet Fernandes']."</strong>";
        ?>
        </body>
        </html>
        
      • In the above code we have declared a $salary array. It contains salary for the employees.
      • An individual element from the salary array is displayed using the following statement:
      • echo "Salary of Robbin = <strong>Rs.".$salary["Robbin"]."/-</strong><br><br>";
      • Next the whole array is displayed using foreach loop as follows:
      •         foreach($salary as $s=>$s_value)
        	{
        		echo "<strong>".$s."=>".$s_value."</strong><br>";
        	}
      • Here, the $s in foreach loop denotes the key in the array $salary and $s_value denotes the value of the respective key.
      • Next we have declared a array $profession using another method to create an array.
      • The output is shown below:
      • associative_arrays_output
        fig 2

    3. Multidimensional Arrays:
      • In PHP, multidimensional arrays are the arrays that contain one or more arrays in it and values in these arrays are accessed using multiple indexes.
      • In these multidimensional arrays an element ( the values of array are also called as elements) in the main array can be an array and element in the sub-array can also be an array and so on. Thus multidimensional array is a collection of small arrays.
      • Example of multidimensional array is shown below:
      • $products=array(
                        “Cloths”=>array(
                                 “Kids wear”=>array(frock,                         
                                                    jeans,
                                                    shirts, 
                                                   t-shirts)),
                                 “Ladies wear”,
                                 “Gents wear”
                                 ),
                         "Stationary”=>array(
                                             "Notebook”=>25,
                                             “Pen”=>20,
                                             “Pencil”=>5
                                             ),
                         “Miscellaneous”=>array(
                                                “CD”=>10,
                                                “DVD”=>16
                                                )
                         );
        
      • In the above example we can see three elements Cloths, Stationary and Miscellaneous products in the $products array.
      • All the three elements are declared as arrays.
      • Moreover one element in the Cloths array i.e. Kids wear is also declared as an array.
      • These elements can be accessed using multiple indexes. For example price for Notebook can be accessed as
        $products[‘Stationary’][‘Notebook’];
      • Let us see an example to demonstrate the multi-dimensional array:
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Arrays</title>
        </head>
        <body>
        <h3>Demonstration of Multidimensional Arrays</h3>
        
        <?php
        	//creating multidimentional array
        	
        	$marks=array("Sakshi"=>array("Hindi"=>78,"Marathi"=>75,"English"=>70),"Priti"=>array("Hindi"=>80,"Marathi"=>78,"English"=>68));
        	
        	echo "<strong>Marks secured by Sakshi in English = ".$marks['Sakshi']['English']."</strong><br><br>";
        	echo "<strong>Marks secured by Priti in English = ".$marks['Priti']['English']."</strong><br><br>";
        	echo "<strong>Marks secured by Sakshi in Marathi = ".$marks['Sakshi']['Marathi']."</strong><br><br>";
        	echo "<strong>Marks secured by Priti in Marathi = ".$marks['Priti']['Marathi']."</strong><br><br>";
        ?>
        </body>
        </html>
        
      • In the above code, we have declared a multidimensional array $marks.
      • The values in multidimensional arrays can be displayed using for example $marks[‘Sakshi’][‘English’] as shown in above code.
      • The output is shown below:
      • multidimensional_arrays_output
        fig 3

Thus we learned the basics of arrays in this PHP Arrays tutorial.

Previous articlePHP Array Operations
Next articlePHP String Functions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -