Loading...

PHP Arrays


In php arrays are use store multiple values in a single variable. an array() is used to create an array of similar items in php.
there are three types of arrays in php language.

1. Index Array

Index arrays always starts with 0 means first entry in an arrays starts with 0 (index). we can access value in an array by using index value of item in an array.
there are two ways to create an index array.
for example :
        		     				    	        	
<?php
    $users = array("peter", "chris", "john", "maria", "angelina", "saturday", "sunday");
    echo "user is : $users[0]";
?>        		     				    	        		
        		     				    	        	
        		     				    	        
Output :
user is peter

we can assign index manually like this also :
        		     			    		    		
<?php
 $weekdays[0] = "sunday";
 $weekdays[1] = "monday";
 $weekdays[2] = "tuesday";
 $weekdays[3] = "wednesday";
 $weekdays[4] = "thursday";
 $weekdays[5] = "friday";
 $weekdays[6] = "saturday";
 echo "today is : $weekdays[0]";
?>
        		     			    		    		
        		     			    		    	
Output :
today is sunday

both above two ways of creating index arrays are same in php.
2. Associative Array

In php associative arrays are the arrays in which we assign values by using key => value pair. we access values by using keys in the array.
there are two ways to create an associative array in php.
for example :
            		     					    	 	
<?php
   $salary = array("John"=>"5000", "Peter"=> "7000", "Steve"=> "9000");             		     					    	 		
   echo "salary of Steve is : ".$salary['Steve'];
?>
            		     					    	 	
            		     					    	 
Output :
Salary of Steve is : 9000
Or
            		     					    	 	
<?php
   $salary["John"] = "5000";
   $salary["Peter"] = "7000";
   $salary["Steve"] = "9000";             		     					    	 		
   echo "salary of Steve is : ".$salary['Steve'];
?>
            		     					    	 	
            		     					    	 
Output :
Salary of Steve is : 9000
3. Multidimensional Array

In php multidimensional array is an array contain one or more arrays in it. we can contain more than one arrays in it means two, three, four etc. but it becomes unmanageable if it contains more than 3. so use it carefully.

we take 2 dimensional in an example for easy to understand.
for example :
        		     					    		
<?php
    $cars = array(array(1, 2016, "BMW"), array(2, 2017, "Toyota"), array(3, 2018, "Honda"));
    // array contains 3 entries. so, $cars[0] = array(1, 2016, "BMW").
    // which again an array of 3 entries. so, $cars[0][0] = 1.
    echo "Car Rank : ".$cars[0][0]."<br>";
    echo "Year : ".$cars[0][1]."<br>";
    echo "Company : ".$cars[0][2]."<br>";
?>        		     					    			
        		     					    		
        		     					    	
Output :
Car Rank : 1
Year : 2016
Company : BMW