2. Introduction to Array
• Arrays is a collection of similar type of elements, but in PHP you can
have the elements of mixed type together in single array.
• In each PHP, each element has two parts:
• Key
• Value
• The key represents the index at which the value of element can be
stored.
• The keys are positive integers that are in ascending order.
3. Array Creation
• There are many ways to create an array in PHP.
• The first way is to use the current array.
• $mylist=array(10,20,30,40,50);
• The second way is to assign the value directly to the array.
• $mylist[0]=10;
• An empty array can also be created using the array construct.
• $mylist=array();
• We can have mixed type of elements in the array.
• $mylist=array(“Tarang”=>”Vadodara”,”Mandar”=>7.5);
4. Accessing Array Elements
• Using an array subscript we can access the array element. The value
of subscript is enclosed within the square brackets.
• $Citycode[‘Vadodara’]=0265;
• $Name[0]=“Tarang”;
• Multiple values can be set to a single scalar variable using array.
• $people=array(“Tarang”,”Mandar”,”Shivang”);
• List($operator,$accountant,$manager)=$people;
• By this assignment Tarang becomes operator, Mandar becomes
accountant and Shivang becomes the manager.
5. Types of Array in PHP
PHP supports three types of array:
•Numeric Arrays
•Associative Arrays
•Multidimensional Arrays
6. Numeric Array
• A numeric array stores each element with a numeric ID key.
• There are two ways to write a numeric array.
• Automatically
• $names = array("Peter","Quagmire","Joe");
• Manually
• $names[0] = "Peter"; $names[1] = "Quagmire";
• $names[2] = "Joe";
• $name[] =”Peter”; $name[] =“Quagmire”; $name[] = “joe”;
8. Associative Array
• An associative array, each ID key is associated with a value.
• When storing data about specific named values, a numerical array is
not always the best way to do it.
• With associative arrays we can use the values as keys and assign
values to them.
• Example: Using array to assign age to a person.
• $ages = array(”Brent"=>42, ”Andrew"=>25, "Joshua”=>16);
• $ages[ Brent'] = 42;‟
• $ages['Joshua'] = 16;
10. Multidimensional Array
• In a multidimensional array, each element in the main array can also
be an array.
• And each element in the sub-array can be an array, and so on.
• Example:
• $shopping=array(array(“Banana”,30),array(Orange,70),array(“Mango”,100));
• echo $shopping[0][0].” costs Rs. “.$shopping[0][1].”<br/>”;
• echo $shopping[1][0].” costs Rs. “.$shopping[1][1].”<br/>”;
• echo $shopping[2][0].” costs Rs. “.$shopping[2][1].”<br/>”;
12. Finding the Size of an Array
• The count() function is used to find the number of elements in the
array.
• Example:
• $icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco
Dip'=>290,'Oreo Cherry'=>250);
• print "There are ".count($icecream_menu) ." flavours of icecreams
available!!"
• Output
• There are 4 flavours of icecreams available!!